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 D999 {
public static void main(String args[])throws IOException
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
int req=n/m;
int arr[]=new int[n+1];
int size[]=new int[m];
List<Integer> list[]=new ArrayList[m];
for(int i=0;i<m;i++)
{
list[i]=new ArrayList<>();
}
for(int i=1;i<=n;i++)
{
arr[i]=sc.nextInt();
size[arr[i]%m]++;
list[arr[i]%m].add(i);
}
long tot=0;int x=0,y=0;
List<Integer> idx=new ArrayList<>();
for(int i=0;i < 2*m;i++)
{
//System.out.println(i+" "+size[i%m]);
if(size[i%m]>req)
{
for(int j=0;j<size[i%m]-req;j++)
{
idx.add(list[i%m].get(j));
y++;
}
size[i%m]=req;
//System.out.println(i+" "+x+" "+y);
}
else if(size[i%m]<req)
{
//System.out.println(idx+" "+i);
while(x!=y && size[i%m]<req)
{
int num=arr[idx.get(x)];
int gg=i-num%m;
tot+=gg;
arr[idx.get(x)]+=gg;
x++;
size[i%m]++;
}
}
}
System.out.println(tot);
for(int i=1;i<=n;i++)
{
System.out.print(arr[i]+" ");
}
}
} | linear | 999_D. Equalize the Remainders | 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.util.*;
import javax.lang.model.util.ElementScanner6;
import java.io.*;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader inp = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solver solver = new Solver();
solver.solve(inp, out);
out.close();
}
static class Solver {
class pair implements Comparable<pair>{
int i;
long dist;
public pair(int i,long dist)
{
this.i=i;
this.dist=dist;
}
public int compareTo(pair p)
{
return Long.compare(this.dist,p.dist);
}
}
class Node implements Comparable < Node > {
int i;
int cnt;
Node(int i, int cnt) {
this.i = i;
this.cnt = cnt;
}
public int compareTo(Node n) {
if (this.cnt == n.cnt) {
return Integer.compare(this.i, n.i);
}
return Integer.compare(this.cnt, n.cnt);
}
}
public boolean done(int[] sp, int[] par) {
int root;
root = findSet(sp[0], par);
for (int i = 1; i < sp.length; i++) {
if (root != findSet(sp[i], par))
return false;
}
return true;
}
public int findSet(int i, int[] par) {
int x = i;
boolean flag = false;
while (par[i] >= 0) {
flag = true;
i = par[i];
}
if (flag)
par[x] = i;
return i;
}
public void unionSet(int i, int j, int[] par) {
int x = findSet(i, par);
int y = findSet(j, par);
if (x < y) {
par[y] = x;
} else {
par[x] = y;
}
}
public long pow(long a, long b, long MOD) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2, MOD);
if (b % 2 == 0) {
return val * val % MOD;
} else {
return val * (val * a % MOD) % MOD;
}
}
public boolean isPrime(int n)
{
for(int i=2;i<n;i++)
{
if(n%i==0)
{
return false;
}
}
return true;
}
public void minPrimeFactor(int n, int[] s) {
boolean prime[] = new boolean[n + 1];
Arrays.fill(prime, true);
s[1] = 1;
s[2] = 2;
for (int i = 4; i <= n; i += 2) {
prime[i] = false;
s[i] = 2;
}
for (int i = 3; i <= n; i += 2) {
if (prime[i]) {
s[i] = i;
for (int j = 2 * i; j <= n; j += i) {
prime[j] = false;
s[j] = i;
}
}
}
}
public void findAllPrime(int n, ArrayList < Node > al, int s[]) {
int curr = s[n];
int cnt = 1;
while (n > 1) {
n /= s[n];
if (curr == s[n]) {
cnt++;
continue;
}
Node n1 = new Node(curr, cnt);
al.add(n1);
curr = s[n];
cnt = 1;
}
}
public int binarySearch(int n, int k) {
int left = 1;
int right = 100000000 + 5;
int ans = 0;
while (left <= right) {
int mid = (left + right) / 2;
if (n / mid >= k) {
left = mid + 1;
ans = mid;
} else {
right = mid - 1;
}
}
return ans;
}
public boolean checkPallindrom(String s) {
char ch[] = s.toCharArray();
for (int i = 0; i < s.length() / 2; i++) {
if (ch[i] != ch[s.length() - 1 - i])
return false;
}
return true;
}
public void remove(ArrayList < Integer > [] al, int x) {
for (int i = 0; i < al.length; i++) {
for (int j = 0; j < al[i].size(); j++) {
if (al[i].get(j) == x)
al[i].remove(j);
}
}
}
public long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
public void printDivisors(long n, ArrayList < Long > al) {
// Note that this loop runs till square root
for (long i = 1; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
// If divisors are equal, print only one
if (n / i == i) {
al.add(i);
} else // Otherwise print both
{
al.add(i);
al.add(n / i);
}
}
}
}
public static long constructSegment(long seg[], long arr[], int low, int high, int pos) {
if (low == high) {
seg[pos] = arr[low];
return seg[pos];
}
int mid = (low + high) / 2;
long t1 = constructSegment(seg, arr, low, mid, (2 * pos) + 1);
long t2 = constructSegment(seg, arr, mid + 1, high, (2 * pos) + 2);
seg[pos] = t1 + t2;
return seg[pos];
}
public static long querySegment(long seg[], int low, int high, int qlow, int qhigh, int pos) {
if (qlow <= low && qhigh >= high) {
return seg[pos];
} else if (qlow > high || qhigh < low) {
return 0;
} else {
long ans = 0;
int mid = (low + high) / 2;
ans += querySegment(seg, low, mid, qlow, qhigh, (2 * pos) + 1);
ans += querySegment(seg, mid + 1, high, qlow, qhigh, (2 * pos) + 2);
return ans;
}
}
public static int lcs(char[] X, char[] Y, int m, int n) {
if (m == 0 || n == 0)
return 0;
if (X[m - 1] == Y[n - 1])
return 1 + lcs(X, Y, m - 1, n - 1);
else
return Integer.max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n));
}
public static long recursion(long start, long end, long cnt[], int a, int b) {
long min = 0;
long count = 0;
int ans1 = -1;
int ans2 = -1;
int l = 0;
int r = cnt.length - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (cnt[mid] >= start) {
ans1 = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
l = 0;
r = cnt.length - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (cnt[mid] <= end) {
ans2 = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
if (ans1 == -1 || ans2 == -1 || ans2 < ans1) {
// System.out.println("min1 "+min);
min = a;
return a;
} else {
min = b * (end - start + 1) * (ans2 - ans1 + 1);
}
if (start == end) {
// System.out.println("min "+min);
return min;
}
long mid = (end + start) / 2;
min = Long.min(min, recursion(start, mid, cnt, a, b) + recursion(mid + 1, end, cnt, a, b));
// System.out.println("min "+min);
return min;
}
public int dfs_util(ArrayList < Integer > [] al, boolean vis[], int x, int[] s, int lvl[]) {
vis[x] = true;
int cnt = 1;
for (int i = 0; i < al[x].size(); i++) {
if (!vis[al[x].get(i)]) {
lvl[al[x].get(i)] = lvl[x] + 1;
cnt += dfs_util(al, vis, al[x].get(i), s, lvl);
}
}
s[x] = cnt;
return s[x];
}
public void dfs(ArrayList[] al, int[] s, int[] lvl) {
boolean vis[] = new boolean[al.length];
for (int i = 0; i < al.length; i++) {
if (!vis[i]) {
lvl[i] = 1;
dfs_util(al, vis, i, s, lvl);
}
}
}
public int[] computeLps(String s)
{
int ans[] =new int[s.length()];
char ch[] = s.toCharArray();
int n = s.length();
int i=1;
int len=0;
ans[0]=0;
while(i<n)
{
if(ch[i]==ch[len])
{
len++;
ans[i]=len;
i++;
}
else
{
if(len!=0)
{
len=ans[len-1];
}
else
{
ans[i]=len;
i++;
}
}
}
return ans;
}
private void solve(InputReader inp, PrintWriter out1) {
int n = inp.nextInt();
int m = inp.nextInt();
long k = inp.nextLong();
long arr[] = new long[n];
for(int i=0;i<n;i++)
{
arr[i] = inp.nextLong();
}
long ans=0;
for(int i=0;i<m;i++)
{
long sum=0;
for(int j=i;j<n;j++)
{
if(j%m==i)
{
if(sum<0)
{
sum=0;
}
sum-=k;
}
sum+=arr[j];
ans=Math.max(ans,sum);
}
}
System.out.println(ans);
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
class ele implements Comparable < ele > {
int value;
int i;
boolean flag;
public ele(int value, int i) {
this.value = value;
this.i = i;
this.flag = false;
}
public int compareTo(ele e) {
return Integer.compare(this.value, e.value);
}
} | quadratic | 1197_D. Yet Another Subarray Problem | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class LightItUp {
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());
int m = Integer.parseInt(st.nextToken());
int previous = 0;
int array[] = new int[n+1];
int answer = 0;
StringTokenizer st1 = new StringTokenizer(br.readLine());
for(int i = 0; i < n; i++){
array[i] = Integer.parseInt(st1.nextToken());
if(i % 2 == 0){
answer += (array[i] - previous);
}
previous = array[i];
}
if(n % 2 == 0){
answer += (m - previous);
}
previous = m;
int max = Integer.MAX_VALUE;
while(n-- != 0){
int temp = array[n];
if(n%2 == 0){
array[n] = array[n+1] - (previous - array[n]);
}
else{
array[n] = array[n+1] + (previous - array[n]);
}
previous = temp;
max = Math.min(max, array[n]);
}
if(max>=-1){
System.out.println(answer);
}
else{
System.out.println(answer - (max+1));
}
}
}
| linear | 1000_B. Light It Up | CODEFORCES |
import java.io.*;
import java.util.*;
import java.util.function.Function;
public class Main {
static int N;
static int[] U, V;
static int[] A;
public static void main(String[] args) {
FastScanner sc = new FastScanner(System.in);
N = sc.nextInt();
U = new int[N-1];
V = new int[N-1];
for (int i = 0; i < N - 1; i++) {
U[i] = sc.nextInt()-1;
V[i] = sc.nextInt()-1;
}
A = sc.nextIntArray(N, -1);
System.out.println(solve() ? "Yes" : "No");
}
static boolean solve() {
if( A[0] != 0 ) return false;
int[][] G = adjB(N, U, V);
Map<Integer, Integer> parents = new HashMap<>();
for (Node node : orderFromRoot(N, G, 0)) {
parents.put(node.a, node.parent);
}
ArrayDeque<Integer> q = new ArrayDeque<>();
for (int next : G[0]) {
q.add(0);
}
int idx = 1;
while(!q.isEmpty()) {
int p = q.poll();
int a = A[idx++];
if( parents.get(a) != p ) {
return false;
}
for (int next : G[a]) {
if( next == p ) continue;
q.add(a);
}
}
return true;
}
static int[][] adjB(int n, int[] from, int[] to) {
int[][] adj = new int[n][];
int[] cnt = new int[n];
for (int f : from) {
cnt[f]++;
}
for (int t : to) {
cnt[t]++;
}
for (int i = 0; i < n; i++) {
adj[i] = new int[cnt[i]];
}
for (int i = 0; i < from.length; i++) {
adj[from[i]][--cnt[from[i]]] = to[i];
adj[to[i]][--cnt[to[i]]] = from[i];
}
return adj;
}
static Node[] orderFromRoot(int N, int[][] G, int root) {
ArrayDeque<Node> q = new ArrayDeque<>();
Node[] ret = new Node[N];
int idx = 0;
q.add(new Node(-1, root));
while(!q.isEmpty()) {
Node n = q.poll();
ret[idx++] = n;
for (int next : G[n.a]) {
if( next == n.parent ) continue;
q.add(new Node(n.a, next));
}
}
return ret;
}
static class Node {
int parent, a;
public Node(int parent, int a) {
this.parent = parent;
this.a = a;
}
}
@SuppressWarnings("unused")
static class FastScanner {
private BufferedReader reader;
private StringTokenizer tokenizer;
FastScanner(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
tokenizer = null;
}
String next() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
String nextLine() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken("\n");
}
long nextLong() {
return Long.parseLong(next());
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
int[] nextIntArray(int n, int delta) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt() + delta;
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
}
static <A> void writeLines(A[] as, Function<A, String> f) {
PrintWriter pw = new PrintWriter(System.out);
for (A a : as) {
pw.println(f.apply(a));
}
pw.flush();
}
static void writeLines(int[] as) {
PrintWriter pw = new PrintWriter(System.out);
for (int a : as) pw.println(a);
pw.flush();
}
static void writeLines(long[] as) {
PrintWriter pw = new PrintWriter(System.out);
for (long a : as) pw.println(a);
pw.flush();
}
static int max(int... as) {
int max = Integer.MIN_VALUE;
for (int a : as) max = Math.max(a, max);
return max;
}
static int min(int... as) {
int min = Integer.MAX_VALUE;
for (int a : as) min = Math.min(a, min);
return min;
}
static void debug(Object... args) {
StringJoiner j = new StringJoiner(" ");
for (Object arg : args) {
if (arg instanceof int[]) j.add(Arrays.toString((int[]) arg));
else if (arg instanceof long[]) j.add(Arrays.toString((long[]) arg));
else if (arg instanceof double[]) j.add(Arrays.toString((double[]) arg));
else if (arg instanceof Object[]) j.add(Arrays.toString((Object[]) arg));
else j.add(arg.toString());
}
System.err.println(j.toString());
}
}
| nlogn | 1037_D. Valid BFS? | CODEFORCES |
import java.util.*;
import java.io.*;
public class Solution
{
public static void main(String [] args) throws IOException
{
PrintWriter pw=new PrintWriter(System.out);//use pw.println() not pw.write();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer(br.readLine());
/*
inputCopy
5 3
xyabd
outputCopy
29
inputCopy
7 4
problem
outputCopy
34
inputCopy
2 2
ab
outputCopy
-1
inputCopy
12 1
abaabbaaabbb
outputCopy
1
*/
int n=Integer.parseInt(st.nextToken());
int k=Integer.parseInt(st.nextToken());
st=new StringTokenizer(br.readLine());
String str=st.nextToken();
char [] arr=str.toCharArray();
Arrays.sort(arr);
int weight=arr[0]-96;
char a=arr[0];
int included=1;
for(int i=1;i<arr.length;++i)
{
if(included==k)
break;
char c=arr[i];
if(c-a<2)
continue;
weight+=arr[i]-96;
++included;
a=arr[i];
}
if(included==k)
pw.println(weight);
else
pw.println(-1);
pw.close();//Do not forget to write it after every program return statement !!
}
}
/*
→Judgement Protocol
Test: #1, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
5 3
xyabd
Output
29
Answer
29
Checker Log
ok 1 number(s): "29"
Test: #2, time: 78 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
7 4
problem
Output
34
Answer
34
Checker Log
ok 1 number(s): "34"
Test: #3, time: 139 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
2 2
ab
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #4, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
12 1
abaabbaaabbb
Output
1
Answer
1
Checker Log
ok 1 number(s): "1"
Test: #5, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
50 13
qwertyuiopasdfghjklzxcvbnmaaaaaaaaaaaaaaaaaaaaaaaa
Output
169
Answer
169
Checker Log
ok 1 number(s): "169"
Test: #6, time: 108 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
50 14
qwertyuiopasdfghjklzxcvbnmaaaaaaaaaaaaaaaaaaaaaaaa
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #7, time: 93 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
1 1
a
Output
1
Answer
1
Checker Log
ok 1 number(s): "1"
Test: #8, time: 108 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
50 1
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Output
1
Answer
1
Checker Log
ok 1 number(s): "1"
Test: #9, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
50 2
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #10, time: 92 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
13 13
uwgmkyqeiaocs
Output
169
Answer
169
Checker Log
ok 1 number(s): "169"
Test: #11, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
13 13
hzdxpbfvrltnj
Output
182
Answer
182
Checker Log
ok 1 number(s): "182"
Test: #12, time: 93 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
1 1
n
Output
14
Answer
14
Checker Log
ok 1 number(s): "14"
Test: #13, time: 92 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
10 8
smzeblyjqw
Output
113
Answer
113
Checker Log
ok 1 number(s): "113"
Test: #14, time: 78 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
20 20
tzmvhskkyugkuuxpvtbh
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #15, time: 109 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
30 15
wjzolzzkfulwgioksfxmcxmnnjtoav
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #16, time: 93 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
40 30
xumfrflllrrgswehqtsskefixhcxjrxbjmrpsshv
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #17, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
50 31
ahbyyoxltryqdmvenemaqnbakglgqolxnaifnqtoclnnqiabpz
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #18, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
10 7
iuiukrxcml
Output
99
Answer
99
Checker Log
ok 1 number(s): "99"
Test: #19, time: 109 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
38 2
vjzarfykmrsrvwbwfwldsulhxtykmjbnwmdufa
Output
5
Answer
5
Checker Log
ok 1 number(s): "5"
Test: #20, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
12 6
fwseyrarkwcd
Output
61
Answer
61
Checker Log
ok 1 number(s): "61"
Test: #21, time: 109 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
2 2
ac
Output
4
Answer
4
Checker Log
ok 1 number(s): "4"
Test: #22, time: 108 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
1 1
c
Output
3
Answer
3
Checker Log
ok 1 number(s): "3"
Test: #23, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
2 2
ad
Output
5
Answer
5
Checker Log
ok 1 number(s): "5"
Test: #24, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 1, verdict: WRONG_ANSWER
Input
2 1
ac
Output
-1
Answer
1
Checker Log
wrong answer 1st number
*/ | linear | 1011_A. Stages | CODEFORCES |
import java.util.*;
public class A
{
public static int palin(String str)
{
int flag=0;
int l=str.length();
for(int i=0;i<l/2;i++)
{
if(str.charAt(i)!=str.charAt(l-i-1))
{
flag=1;
break;
}
}
if(flag==1)
return 0;
else
return 1;
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String str=sc.next();
HashSet<Character> hs=new HashSet<>();
for(int i=0;i<str.length();i++)
{
hs.add(str.charAt(i));
}
if(hs.size()==1)
System.out.println(0);
else if(palin(str)==0)
System.out.println(str.length());
else
System.out.println(str.length()-1);
}
} | linear | 981_A. Antipalindrome | CODEFORCES |
import java.io.*;
import java.util.*;
import java.lang.*;
import java.awt.*;
import java.awt.geom.*;
import java.math.*;
import java.text.*;
import java.math.BigInteger.*;
import java.util.Arrays;
public class CF111111
{
BufferedReader in;
StringTokenizer as;
int nums[],nums2[];
int[] nums1[];
boolean con = true;
ArrayList < Integer > ar = new ArrayList < Integer >();
ArrayList < Integer > fi = new ArrayList < Integer >();
Map<Integer,Integer > map = new HashMap<Integer, Integer>();
public static void main (String[] args)
{
new CF111111 ();
}
public int GCD(int a, int b) {
if (b==0) return a;
return GCD(b,a%b);
}
public int LIS(int arr[])
{
int n = arr.length;
int sun[] = new int [n];
int cur = 0;
for(int x = 0;x<n;x++)
{
int temp = Arrays.binarySearch(sun,0,cur,arr[x]);
if(temp < 0)
temp = -temp -1;
sun[temp] = arr[x];
if(temp == cur)
cur++;
}
return cur;
}
public CF111111 ()
{
try
{
in = new BufferedReader (new InputStreamReader (System.in));
int a = nextInt();
for(int xx1 = 0;xx1<a;xx1++)
{
int b = nextInt();
nums = new int [b];
for(int x = 0;x<b;x++)
{
nums[x] = nextInt();
}
int max = 0;
int max2 = -1;
for(int x = 0;x<b;x++)
{
if(nums[x] >= max)
{
max2 = max;
max = nums[x];
}
else if(nums[x] >= max2)
max2 = nums[x];
}
System.out.println(Math.min(max2, b-1)-1);
}
}
catch(IOException e)
{
}
}
String next () throws IOException
{
while (as == null || !as.hasMoreTokens ())
{
as = new StringTokenizer (in.readLine ().trim ());
}
return as.nextToken ();
}
long nextLong () throws IOException
{
return Long.parseLong (next ());
}
int nextInt () throws IOException
{
return Integer.parseInt (next ());
}
double nextDouble () throws IOException
{
return Double.parseDouble (next ());
}
String nextLine () throws IOException
{
return in.readLine ().trim ();
}
} | linear | 1197_A. DIY Wooden Ladder | CODEFORCES |
import java.io.*;
import java.util.Scanner;
public class abc{
public static int check(StringBuilder s)
{
int countRemove=0;
if(!s.toString().contains("xxx")) return countRemove;
else{
for(int i=1;i<s.length()-1;i++)
{
if(s.charAt(i-1)=='x' && s.charAt(i)=='x' && s.charAt(i+1)=='x')
{
countRemove++;
}
}
return countRemove;
}
}
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
//sc= new Scanner(System.in);
String s = sc.next();
StringBuilder sb = new StringBuilder("");
sb.append(s);
System.out.println(check(sb));
}
} | linear | 978_B. File Name | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Collection;
import java.util.AbstractList;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Deque;
import java.util.ArrayDeque;
import java.util.NoSuchElementException;
import java.util.ConcurrentModificationException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author cunbidun
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
DPairOfLines solver = new DPairOfLines();
solver.solve(1, in, out);
out.close();
}
static class DPairOfLines {
private static final int INF = (int) 2e9 + 7;
private InputReader in;
private PrintWriter out;
public void solve(int testNumber, InputReader in, PrintWriter out) {
this.in = in;
this.out = out;
int n = in.nextInt();
if (n <= 4) {
out.println("YES");
return;
}
TreeList<PairII> list = new TreeList<>();
PairII[] a = new PairII[n + 1];
for (int i = 1; i <= n; i++) {
a[i] = (new PairII(in.nextInt(), in.nextInt()));
list.add(a[i]);
}
PairII pos1 = new PairII(INF, INF);
PairII pos2 = new PairII(INF, INF);
for (int i = 1; i <= 5; i++) {
for (int j = i + 1; j <= 5; j++) {
for (int k = j + 1; k <= 5; k++) {
int x1 = a[i].first;
int y1 = a[i].second;
int x2 = a[j].first;
int y2 = a[j].second;
int x = a[k].first;
int y = a[k].second;
long s = (long) (y2 - y1) * x + (long) (x1 - x2) * y + ((long) x2 * y1 - (long) x1 * y2);
if (s == 0) {
pos1 = a[i];
pos2 = a[j];
}
}
}
}
if (pos1.equals(new PairII(INF, INF))) {
out.println("NO");
return;
}
int x1 = pos1.first;
int y1 = pos1.second;
int x2 = pos2.first;
int y2 = pos2.second;
for (int i = 0; i < list.size(); i++) {
int x = list.get(i).first;
int y = list.get(i).second;
long s = (long) (y2 - y1) * x + (long) (x1 - x2) * y + ((long) x2 * y1 - (long) x1 * y2);
if (s == 0) {
list.remove(i);
i--;
}
}
if (list.size() <= 2) {
out.println("YES");
return;
}
x1 = list.get(0).first;
y1 = list.get(0).second;
x2 = list.get(1).first;
y2 = list.get(1).second;
for (int i = 0; i < list.size(); i++) {
int x = list.get(i).first;
int y = list.get(i).second;
long s = (long) (y2 - y1) * x + (long) (x1 - x2) * y + ((long) x2 * y1 - (long) x1 * y2);
if (s == 0) {
list.remove(i);
i--;
}
}
if (list.size() == 0) {
out.println("YES");
} else out.println("NO");
}
}
static interface OrderedIterator<E> extends Iterator<E> {
}
static class PairII implements Comparable<PairII> {
public int first;
public int second;
public PairII(int first, int second) {
this.first = first;
this.second = second;
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PairII pair = (PairII) o;
return first == pair.first && second == pair.second;
}
public String toString() {
return "(" + first + "," + second + ")";
}
public int compareTo(PairII o) {
int value = Integer.compare(first, o.first);
if (value != 0) {
return value;
}
return Integer.compare(second, o.second);
}
}
static class TreeList<E> extends AbstractList<E> {
private TreeList.AVLNode<E> root;
private int size;
public TreeList() {
super();
}
public TreeList(final Collection<? extends E> coll) {
super();
if (!coll.isEmpty()) {
root = new TreeList.AVLNode<>(coll);
size = coll.size();
}
}
public E get(final int index) {
return root.get(index).getValue();
}
public int size() {
return size;
}
public Iterator<E> iterator() {
// override to go 75% faster
return listIterator(0);
}
public ListIterator<E> listIterator() {
// override to go 75% faster
return listIterator(0);
}
public ListIterator<E> listIterator(final int fromIndex) {
return new TreeList.TreeListIterator<>(this, fromIndex);
}
public int indexOf(final Object object) {
// override to go 75% faster
if (root == null) {
return -1;
}
return root.indexOf(object, root.relativePosition);
}
public boolean contains(final Object object) {
return indexOf(object) >= 0;
}
public Object[] toArray() {
final Object[] array = new Object[size()];
if (root != null) {
root.toArray(array, root.relativePosition);
}
return array;
}
public void add(final int index, final E obj) {
modCount++;
if (root == null) {
root = new TreeList.AVLNode<>(index, obj, null, null);
} else {
root = root.insert(index, obj);
}
size++;
}
public boolean addAll(final Collection<? extends E> c) {
if (c.isEmpty()) {
return false;
}
modCount += c.size();
final TreeList.AVLNode<E> cTree = new TreeList.AVLNode<>(c);
root = root == null ? cTree : root.addAll(cTree, size);
size += c.size();
return true;
}
public E set(final int index, final E obj) {
final TreeList.AVLNode<E> node = root.get(index);
final E result = node.value;
node.setValue(obj);
return result;
}
public E remove(final int index) {
modCount++;
final E result = get(index);
root = root.remove(index);
size--;
return result;
}
public void clear() {
modCount++;
root = null;
size = 0;
}
static class AVLNode<E> {
private TreeList.AVLNode<E> left;
private boolean leftIsPrevious;
private TreeList.AVLNode<E> right;
private boolean rightIsNext;
private int height;
private int relativePosition;
private E value;
private AVLNode(final int relativePosition, final E obj,
final TreeList.AVLNode<E> rightFollower, final TreeList.AVLNode<E> leftFollower) {
this.relativePosition = relativePosition;
value = obj;
rightIsNext = true;
leftIsPrevious = true;
right = rightFollower;
left = leftFollower;
}
private AVLNode(final Collection<? extends E> coll) {
this(coll.iterator(), 0, coll.size() - 1, 0, null, null);
}
private AVLNode(final Iterator<? extends E> iterator, final int start, final int end,
final int absolutePositionOfParent, final TreeList.AVLNode<E> prev, final TreeList.AVLNode<E> next) {
final int mid = start + (end - start) / 2;
if (start < mid) {
left = new TreeList.AVLNode<>(iterator, start, mid - 1, mid, prev, this);
} else {
leftIsPrevious = true;
left = prev;
}
value = iterator.next();
relativePosition = mid - absolutePositionOfParent;
if (mid < end) {
right = new TreeList.AVLNode<>(iterator, mid + 1, end, mid, this, next);
} else {
rightIsNext = true;
right = next;
}
recalcHeight();
}
E getValue() {
return value;
}
void setValue(final E obj) {
this.value = obj;
}
TreeList.AVLNode<E> get(final int index) {
final int indexRelativeToMe = index - relativePosition;
if (indexRelativeToMe == 0) {
return this;
}
final TreeList.AVLNode<E> nextNode = indexRelativeToMe < 0 ? getLeftSubTree() : getRightSubTree();
if (nextNode == null) {
return null;
}
return nextNode.get(indexRelativeToMe);
}
int indexOf(final Object object, final int index) {
if (getLeftSubTree() != null) {
final int result = left.indexOf(object, index + left.relativePosition);
if (result != -1) {
return result;
}
}
if (value == null ? value == object : value.equals(object)) {
return index;
}
if (getRightSubTree() != null) {
return right.indexOf(object, index + right.relativePosition);
}
return -1;
}
void toArray(final Object[] array, final int index) {
array[index] = value;
if (getLeftSubTree() != null) {
left.toArray(array, index + left.relativePosition);
}
if (getRightSubTree() != null) {
right.toArray(array, index + right.relativePosition);
}
}
TreeList.AVLNode<E> next() {
if (rightIsNext || right == null) {
return right;
}
return right.min();
}
TreeList.AVLNode<E> previous() {
if (leftIsPrevious || left == null) {
return left;
}
return left.max();
}
TreeList.AVLNode<E> insert(final int index, final E obj) {
final int indexRelativeToMe = index - relativePosition;
if (indexRelativeToMe <= 0) {
return insertOnLeft(indexRelativeToMe, obj);
}
return insertOnRight(indexRelativeToMe, obj);
}
private TreeList.AVLNode<E> insertOnLeft(final int indexRelativeToMe, final E obj) {
if (getLeftSubTree() == null) {
setLeft(new TreeList.AVLNode<>(-1, obj, this, left), null);
} else {
setLeft(left.insert(indexRelativeToMe, obj), null);
}
if (relativePosition >= 0) {
relativePosition++;
}
final TreeList.AVLNode<E> ret = balance();
recalcHeight();
return ret;
}
private TreeList.AVLNode<E> insertOnRight(final int indexRelativeToMe, final E obj) {
if (getRightSubTree() == null) {
setRight(new TreeList.AVLNode<>(+1, obj, right, this), null);
} else {
setRight(right.insert(indexRelativeToMe, obj), null);
}
if (relativePosition < 0) {
relativePosition--;
}
final TreeList.AVLNode<E> ret = balance();
recalcHeight();
return ret;
}
private TreeList.AVLNode<E> getLeftSubTree() {
return leftIsPrevious ? null : left;
}
private TreeList.AVLNode<E> getRightSubTree() {
return rightIsNext ? null : right;
}
private TreeList.AVLNode<E> max() {
return getRightSubTree() == null ? this : right.max();
}
private TreeList.AVLNode<E> min() {
return getLeftSubTree() == null ? this : left.min();
}
TreeList.AVLNode<E> remove(final int index) {
final int indexRelativeToMe = index - relativePosition;
if (indexRelativeToMe == 0) {
return removeSelf();
}
if (indexRelativeToMe > 0) {
setRight(right.remove(indexRelativeToMe), right.right);
if (relativePosition < 0) {
relativePosition++;
}
} else {
setLeft(left.remove(indexRelativeToMe), left.left);
if (relativePosition > 0) {
relativePosition--;
}
}
recalcHeight();
return balance();
}
private TreeList.AVLNode<E> removeMax() {
if (getRightSubTree() == null) {
return removeSelf();
}
setRight(right.removeMax(), right.right);
if (relativePosition < 0) {
relativePosition++;
}
recalcHeight();
return balance();
}
private TreeList.AVLNode<E> removeMin() {
if (getLeftSubTree() == null) {
return removeSelf();
}
setLeft(left.removeMin(), left.left);
if (relativePosition > 0) {
relativePosition--;
}
recalcHeight();
return balance();
}
private TreeList.AVLNode<E> removeSelf() {
if (getRightSubTree() == null && getLeftSubTree() == null) {
return null;
}
if (getRightSubTree() == null) {
if (relativePosition > 0) {
left.relativePosition += relativePosition;
}
left.max().setRight(null, right);
return left;
}
if (getLeftSubTree() == null) {
right.relativePosition += relativePosition - (relativePosition < 0 ? 0 : 1);
right.min().setLeft(null, left);
return right;
}
if (heightRightMinusLeft() > 0) {
// more on the right, so delete from the right
final TreeList.AVLNode<E> rightMin = right.min();
value = rightMin.value;
if (leftIsPrevious) {
left = rightMin.left;
}
right = right.removeMin();
if (relativePosition < 0) {
relativePosition++;
}
} else {
// more on the left or equal, so delete from the left
final TreeList.AVLNode<E> leftMax = left.max();
value = leftMax.value;
if (rightIsNext) {
right = leftMax.right;
}
final TreeList.AVLNode<E> leftPrevious = left.left;
left = left.removeMax();
if (left == null) {
// special case where left that was deleted was a double link
// only occurs when height difference is equal
left = leftPrevious;
leftIsPrevious = true;
}
if (relativePosition > 0) {
relativePosition--;
}
}
recalcHeight();
return this;
}
private TreeList.AVLNode<E> balance() {
switch (heightRightMinusLeft()) {
case 1:
case 0:
case -1:
return this;
case -2:
if (left.heightRightMinusLeft() > 0) {
setLeft(left.rotateLeft(), null);
}
return rotateRight();
case 2:
if (right.heightRightMinusLeft() < 0) {
setRight(right.rotateRight(), null);
}
return rotateLeft();
default:
throw new RuntimeException("tree inconsistent!");
}
}
private int getOffset(final TreeList.AVLNode<E> node) {
if (node == null) {
return 0;
}
return node.relativePosition;
}
private int setOffset(final TreeList.AVLNode<E> node, final int newOffest) {
if (node == null) {
return 0;
}
final int oldOffset = getOffset(node);
node.relativePosition = newOffest;
return oldOffset;
}
private void recalcHeight() {
height = Math.max(
getLeftSubTree() == null ? -1 : getLeftSubTree().height,
getRightSubTree() == null ? -1 : getRightSubTree().height) + 1;
}
private int getHeight(final TreeList.AVLNode<E> node) {
return node == null ? -1 : node.height;
}
private int heightRightMinusLeft() {
return getHeight(getRightSubTree()) - getHeight(getLeftSubTree());
}
private TreeList.AVLNode<E> rotateLeft() {
final TreeList.AVLNode<E> newTop = right; // can't be faedelung!
final TreeList.AVLNode<E> movedNode = getRightSubTree().getLeftSubTree();
final int newTopPosition = relativePosition + getOffset(newTop);
final int myNewPosition = -newTop.relativePosition;
final int movedPosition = getOffset(newTop) + getOffset(movedNode);
setRight(movedNode, newTop);
newTop.setLeft(this, null);
setOffset(newTop, newTopPosition);
setOffset(this, myNewPosition);
setOffset(movedNode, movedPosition);
return newTop;
}
private TreeList.AVLNode<E> rotateRight() {
final TreeList.AVLNode<E> newTop = left;
final TreeList.AVLNode<E> movedNode = getLeftSubTree().getRightSubTree();
final int newTopPosition = relativePosition + getOffset(newTop);
final int myNewPosition = -newTop.relativePosition;
final int movedPosition = getOffset(newTop) + getOffset(movedNode);
setLeft(movedNode, newTop);
newTop.setRight(this, null);
setOffset(newTop, newTopPosition);
setOffset(this, myNewPosition);
setOffset(movedNode, movedPosition);
return newTop;
}
private void setLeft(final TreeList.AVLNode<E> node, final TreeList.AVLNode<E> previous) {
leftIsPrevious = node == null;
left = leftIsPrevious ? previous : node;
recalcHeight();
}
private void setRight(final TreeList.AVLNode<E> node, final TreeList.AVLNode<E> next) {
rightIsNext = node == null;
right = rightIsNext ? next : node;
recalcHeight();
}
private TreeList.AVLNode<E> addAll(TreeList.AVLNode<E> otherTree, final int currentSize) {
final TreeList.AVLNode<E> maxNode = max();
final TreeList.AVLNode<E> otherTreeMin = otherTree.min();
// We need to efficiently merge the two AVL trees while keeping them
// balanced (or nearly balanced). To do this, we take the shorter
// tree and combine it with a similar-height subtree of the taller
// tree. There are two symmetric cases:
// * this tree is taller, or
// * otherTree is taller.
if (otherTree.height > height) {
// CASE 1: The other tree is taller than this one. We will thus
// merge this tree into otherTree.
// STEP 1: Remove the maximum element from this tree.
final TreeList.AVLNode<E> leftSubTree = removeMax();
// STEP 2: Navigate left from the root of otherTree until we
// contains a subtree, s, that is no taller than me. (While we are
// navigating left, we store the nodes we encounter in a stack
// so that we can re-balance them in step 4.)
final Deque<TreeList.AVLNode<E>> sAncestors = new ArrayDeque<>();
TreeList.AVLNode<E> s = otherTree;
int sAbsolutePosition = s.relativePosition + currentSize;
int sParentAbsolutePosition = 0;
while (s != null && s.height > getHeight(leftSubTree)) {
sParentAbsolutePosition = sAbsolutePosition;
sAncestors.push(s);
s = s.left;
if (s != null) {
sAbsolutePosition += s.relativePosition;
}
}
// STEP 3: Replace s with a newly constructed subtree whose root
// is maxNode, whose left subtree is leftSubTree, and whose right
// subtree is s.
maxNode.setLeft(leftSubTree, null);
maxNode.setRight(s, otherTreeMin);
if (leftSubTree != null) {
leftSubTree.max().setRight(null, maxNode);
leftSubTree.relativePosition -= currentSize - 1;
}
if (s != null) {
s.min().setLeft(null, maxNode);
s.relativePosition = sAbsolutePosition - currentSize + 1;
}
maxNode.relativePosition = currentSize - 1 - sParentAbsolutePosition;
otherTree.relativePosition += currentSize;
// STEP 4: Re-balance the tree and recalculate the heights of s's ancestors.
s = maxNode;
while (!sAncestors.isEmpty()) {
final TreeList.AVLNode<E> sAncestor = sAncestors.pop();
sAncestor.setLeft(s, null);
s = sAncestor.balance();
}
return s;
}
otherTree = otherTree.removeMin();
final Deque<TreeList.AVLNode<E>> sAncestors = new ArrayDeque<>();
TreeList.AVLNode<E> s = this;
int sAbsolutePosition = s.relativePosition;
int sParentAbsolutePosition = 0;
while (s != null && s.height > getHeight(otherTree)) {
sParentAbsolutePosition = sAbsolutePosition;
sAncestors.push(s);
s = s.right;
if (s != null) {
sAbsolutePosition += s.relativePosition;
}
}
otherTreeMin.setRight(otherTree, null);
otherTreeMin.setLeft(s, maxNode);
if (otherTree != null) {
otherTree.min().setLeft(null, otherTreeMin);
otherTree.relativePosition++;
}
if (s != null) {
s.max().setRight(null, otherTreeMin);
s.relativePosition = sAbsolutePosition - currentSize;
}
otherTreeMin.relativePosition = currentSize - sParentAbsolutePosition;
s = otherTreeMin;
while (!sAncestors.isEmpty()) {
final TreeList.AVLNode<E> sAncestor = sAncestors.pop();
sAncestor.setRight(s, null);
s = sAncestor.balance();
}
return s;
}
}
static class TreeListIterator<E> implements ListIterator<E>, OrderedIterator<E> {
private final TreeList<E> parent;
private TreeList.AVLNode<E> next;
private int nextIndex;
private TreeList.AVLNode<E> current;
private int currentIndex;
private int expectedModCount;
private TreeListIterator(final TreeList<E> parent, final int fromIndex) throws IndexOutOfBoundsException {
super();
this.parent = parent;
this.expectedModCount = parent.modCount;
this.next = parent.root == null ? null : parent.root.get(fromIndex);
this.nextIndex = fromIndex;
this.currentIndex = -1;
}
private void checkModCount() {
if (parent.modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
public boolean hasNext() {
return nextIndex < parent.size();
}
public E next() {
checkModCount();
if (!hasNext()) {
throw new NoSuchElementException("No element at index " + nextIndex + ".");
}
if (next == null) {
next = parent.root.get(nextIndex);
}
final E value = next.getValue();
current = next;
currentIndex = nextIndex++;
next = next.next();
return value;
}
public boolean hasPrevious() {
return nextIndex > 0;
}
public E previous() {
checkModCount();
if (!hasPrevious()) {
throw new NoSuchElementException("Already at start of list.");
}
if (next == null) {
next = parent.root.get(nextIndex - 1);
} else {
next = next.previous();
}
final E value = next.getValue();
current = next;
currentIndex = --nextIndex;
return value;
}
public int nextIndex() {
return nextIndex;
}
public int previousIndex() {
return nextIndex() - 1;
}
public void remove() {
checkModCount();
if (currentIndex == -1) {
throw new IllegalStateException();
}
parent.remove(currentIndex);
if (nextIndex != currentIndex) {
// remove() following next()
nextIndex--;
}
// the AVL node referenced by next may have become stale after a remove
// reset it now: will be retrieved by next call to next()/previous() via nextIndex
next = null;
current = null;
currentIndex = -1;
expectedModCount++;
}
public void set(final E obj) {
checkModCount();
if (current == null) {
throw new IllegalStateException();
}
current.setValue(obj);
}
public void add(final E obj) {
checkModCount();
parent.add(nextIndex, obj);
current = null;
currentIndex = -1;
nextIndex++;
expectedModCount++;
}
}
}
static class InputReader extends InputStream {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
private static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
| nlogn | 961_D. Pair Of Lines | CODEFORCES |
import java.io.*;
import java.util.*;
public class GFG {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
int n = sc.nextInt();
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int ans = 0;
int t= sc.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;i++){
int nn = sc.nextInt();
ans+=a;
if(b<c){
ans += (t-nn) * (c - b);
}
}
System.out.println(ans);
}
} | linear | 964_B. Messages | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
744444444747477777774
44444447474747777777
*/
/**
*
* @author Andy Phan
*/
public class b {
public static void main(String[] args) {
FS in = new FS(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
Integer[] arr = new Integer[n];
int numZ = 0;
for(int i = 0; i < n; i++) {
arr[i] = in.nextInt();
if(arr[i] == 0) numZ++;
}
Arrays.sort(arr);
if(numZ > 1) {
System.out.println("cslnb");
return;
}
int numDup = 0;
int[] arr2 = new int[n];
for(int i = 0; i < n; i++) {
arr2[i] = arr[i];
if(i != 0) {
if(arr2[i] == arr2[i-1]) {
arr2[i-1]--;
numDup++;
}
}
}
if(numDup > 1) {
System.out.println("cslnb");
return;
}
for(int i = 0; i < n; i++) {
if(i != 0) {
if(arr2[i] == arr2[i-1]) {
System.out.println("cslnb");
return;
}
}
}
long num = 0;
if(numDup == 1) num++;
for(int i = 0; i < n; i++) {
num += arr2[i]-i;
}
if(num%2 == 0) {
System.out.println("cslnb");
} else {
System.out.println("sjfnb");
}
out.close();
}
static class FS {
BufferedReader in;
StringTokenizer token;
public FS(InputStream str) {
in = new BufferedReader(new InputStreamReader(str));
}
public String next() {
if (token == null || !token.hasMoreElements()) {
try {
token = new StringTokenizer(in.readLine());
} catch (IOException ex) {
}
return next();
}
return token.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| linear | 1191_D. Tokitsukaze, CSL and Stone Game | CODEFORCES |
import java.util.*;
import java.io.*;
public class D {
static final boolean stdin = true;
static final String filename = "";
static FastScanner br;
static PrintWriter pw;
public static void main(String[] args) throws IOException {
if (stdin) {
br = new FastScanner();
pw = new PrintWriter(new OutputStreamWriter(System.out));
} else {
br = new FastScanner(filename + ".in");
pw = new PrintWriter(new FileWriter(filename + ".out"));
}
Solver solver = new Solver();
solver.solve(br, pw);
}
static class Solver {
static long mod = (long) (1e10);
public void solve(FastScanner br, PrintWriter pw) throws IOException {
int n = br.ni();
Integer[] in = br.nIa(n);
TreeSet<Integer> ts = new TreeSet<Integer>();
for (int i = 0; i < n; i++) {
ts.add(in[i]);
}
String twoSol = "";
for (int i = 0; i <= 30; i++) {
for (int j : in) {
if (ts.contains(j + (int) Math.pow(2, i))) {
if (ts.contains(j - (int) Math.pow(2, i))) {
pw.println(3);
pw.println(j + " " + (j + (int) Math.pow(2, i)) + " " + (j - (int) Math.pow(2, i)));
pw.close();
System.exit(0);
}else{
twoSol = (j + " " + (j + (int) Math.pow(2, i)));
}
}
}
}
if (twoSol.isEmpty()) {
pw.println(1);
pw.println(in[0]);
} else {
pw.println(2);
pw.println(twoSol);
}
pw.close();
}
static long gcd(long a, long b) {
if (a > b)
return gcd(b, a);
if (a == 0)
return b;
return gcd(b % a, a);
}
static long lcm(long a, long b) {
return a * (b / gcd(a, b));
}
static long pow(long a, long b) {
if (b == 0)
return 1L;
long val = pow(a, b / 2);
if (b % 2 == 0)
return val * val % mod;
else
return val * val % mod * a % mod;
}
}
static class Point implements Comparable<Point> {
int a;
int b;
Point(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(Point o) {
return this.a - o.a;
}
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
ArrayList<Integer>[] ng(int n, int e) {
ArrayList<Integer>[] adj = new ArrayList[n];
for (int i = 0; i < n; i++) {
adj[i] = new ArrayList<Integer>();
}
for (int i = 0; i < e; i++) {
int a = ni() - 1;
int b = ni() - 1;
adj[a].add(b);
adj[b].add(a);
}
return adj;
}
Integer[] nIa(int n) {
Integer[] arr = new Integer[n];
for (int i = 0; i < n; i++) {
arr[i] = ni();
}
return arr;
}
int[] nia(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = ni();
}
return arr;
}
Long[] nLa(int n) {
Long[] arr = new Long[n];
for (int i = 0; i < n; i++) {
arr[i] = nl();
}
return arr;
}
long[] nla(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nl();
}
return arr;
}
String[] nsa(int n) {
String[] arr = new String[n];
for (int i = 0; i < n; i++) {
arr[i] = nt();
}
return arr;
}
String nt() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int ni() {
return Integer.parseInt(nt());
}
long nl() {
return Long.parseLong(nt());
}
double nd() {
return Double.parseDouble(nt());
}
}
} | nlogn | 988_D. Points and Powers of Two | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
public class Main {
private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws NumberFormatException, IOException {
String[] s = br.readLine().trim().split(" ");
int n = Integer.parseInt(s[0]);
int m = Integer.parseInt(s[1]);
long b[] = new long[n];
s = br.readLine().trim().split(" ");
for(int i = 0; i < n; i++) {
b[i] = Integer.parseInt(s[i]);
}
long g[] = new long[m];
s = br.readLine().trim().split(" ");
for(int i = 0; i < m; i++) {
g[i] = Integer.parseInt(s[i]);
}
Arrays.sort(b);
Arrays.sort(g);
if(g[0] < b[n-1]) {
System.out.println("-1");
}
else if(g[0] == b[n-1]){
long ans = 0;
for(int i = 0; i < m; i++) {
ans += g[i];
}
for(int i = 0; i < n-1; i++) {
ans += (m)*b[i];
}
System.out.println(ans);
}
else {
long ans = 0;
for(int i = 0; i < m; i++) {
ans += g[i];
}
for(int i = 0; i < n-1; i++) {
ans += (m)*b[i];
}
ans += b[n-1]-b[n-2];
System.out.println(ans);
}
}
} | nlogn | 1159_C. The Party and Sweets | CODEFORCES |
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args){
try {
new Main().solve();
} catch (Exception e) {
e.printStackTrace();
}
}
ArrayList<Edge>[]edge;
int n,m,cnt=0;
int ord;
int[]order;int[]vis;
Edge[] e;
private void solve() throws Exception{
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
n=in.nextInt();m=in.nextInt();
edge=new ArrayList[n+1];
e=new Edge[m];
vis=new int[n+1];
order=new int[n+1];
for(int i=1;i<=n;i++){
edge[i]=new ArrayList<>();
}
for(int i=1;i<=m;i++){
int s=in.nextInt(),t=in.nextInt(),c=in.nextInt();
edge[s].add(new Edge(s,t,c,i));
}
int l=0,r=1000000000;
while (l<r){
int mid=(l+r)>>>1;
if(judge(mid,false))r=mid;
else l=mid+1;
}
out.print(l+" ");
judge(l,true);
Arrays.sort(e,0,cnt,Comparator.comparingInt(x->x.id));
int ans=0;
int[]a=new int[m];
for(int i=0;i<cnt;i++){
if(order[e[i].s]<order[e[i].t])a[ans++]=e[i].id;
}
out.println(ans);
for(int i=0;i<ans;i++){
out.print(a[i]+" ");
}
out.println();
out.flush();
}
boolean judge(int min,boolean mod){
Arrays.fill(vis,0);
cycle=false;
for(int i=1;i<=n;i++){
if(vis[i]==0){
dfs(i,min,mod);
if(cycle)return false;
}
}
return true;
}
boolean cycle=false;
void dfs(int cur,int min,boolean mod){
if(cycle)return;
vis[cur]=1;
for(Edge e:edge[cur]){
if(e.c<=min){
if(mod)this.e[cnt++]=e;
continue;
}
if(vis[e.t]==1){
cycle=true;return;
}
else if(vis[e.t]==0)dfs(e.t,min,mod);
}
vis[cur]=2;
if(mod)order[cur]=ord++;
}
}
class Edge{
int s,t,c,id;
Edge(int a,int b,int c,int d){
s=a;t=b;this.c=c;id=d;
}
}
class InputReader{
StreamTokenizer tokenizer;
public InputReader(InputStream stream){
tokenizer=new StreamTokenizer(new BufferedReader(new InputStreamReader(stream)));
tokenizer.ordinaryChars(33,126);
tokenizer.wordChars(33,126);
}
public String next() throws IOException {
tokenizer.nextToken();
return tokenizer.sval;
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public boolean hasNext() throws IOException {
int res=tokenizer.nextToken();
tokenizer.pushBack();
return res!=tokenizer.TT_EOF;
}
} | nlogn | 1100_E. Andrew and Taxi | CODEFORCES |
import java.util.Scanner;
public class origami {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
double n = input.nextInt();
double k = input.nextInt();
double red = 0;
double green = 0;
double blue = 0;
double ans = 0;
red = (2 * n) / k;
green = (5 * n) / k;
blue = (8 * n) / k;
double red1 = Math.ceil(red) ;
double green1 = Math.ceil(green);
double blue1 = Math.ceil(blue);
ans+=red1;
ans+=green1;
ans+=blue1;
Double answer = new Double(ans);
int finished = answer.intValue();
System.out.println(finished);
}
}
| constant | 1080_A. Petya and Origami | CODEFORCES |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.List;
import java.util.StringTokenizer;
public class D {
int[][] fast(int n, int m){
int[][] ans = new int[2][n * m];
int c = 0;
for (int left = 1, right = m; left < right; left++, right--) {
for (int l = 1, r = n; l <= n && r >= 1; l++, r--) {
ans[0][c] = l;
ans[1][c++] = left;
ans[0][c] = r;
ans[1][c++] = right;
}
}
if (m % 2 == 1) {
int x = m/2 + 1;
for(int l = 1, r = n;l < r;l++, r--){
ans[0][c] = l;
ans[1][c++] = x;
ans[0][c] = r;
ans[1][c++] = x;
if(n % 2 == 1 && l + 2 == r){
ans[0][c] = l+1;
ans[1][c++] = x;
}
}
}
if(n == 1 && m % 2 == 1){
ans[0][c] = 1;
ans[1][c] = m/2 + 1;
}
return ans;
}
void stress(){
for(int i = 3;i<=5;i++){
for(int j = 2;j<=5;j++){
int[][] ans = new int[2][];
try{
ans = fast(i, j);
}catch(Exception e){
out.println("ошибка");
out.print(i + " " + j);
return;
}
boolean[][] check = new boolean[i][j];
for(int c = 0;c<ans[0].length;c++){
int x = ans[0][c] - 1;
int y = ans[1][c] - 1;
check[x][y] = true;
}
for(int c = 0;c<i;c++){
for(int q = 0;q<j;q++){
if(!check[c][q]){
out.println(i + " " + j);
out.println("точки");
for(int w = 0;w<ans[0].length;w++){
out.println(ans[0][w] + " " + ans[1][w]);
}
return;
}
}
}
HashSet<String> set = new HashSet<>();
for(int c = 1;c<ans[0].length;c++){
int x = ans[0][c] - ans[0][c- 1];
int y = ans[1][c] - ans[1][c - 1];
set.add(x + " " + y);
}
if(set.size() < i * j - 1){
out.println(i + " " + j);
out.println("вектора");
for(int w = 0;w<ans[0].length;w++){
out.println(ans[0][w] + " " + ans[1][w]);
}
return;
}
}
}
}
void normal(){
int n =readInt();
int m = readInt();
int[][] ans = fast(n, m);
for(int i = 0;i<ans[0].length;i++){
out.println(ans[0][i] + " " + ans[1][i]);
}
}
boolean stress = false;
void solve(){
if(stress) stress();
else normal();
}
public static void main(String[] args) {
new D().run();
}
void run(){
init();
solve();
out.close();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init(){
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
String readLine(){
try{
return in.readLine();
}catch(Exception ex){
throw new RuntimeException(ex);
}
}
String readString(){
while(!tok.hasMoreTokens()){
String nextLine = readLine();
if(nextLine == null) return null;
tok = new StringTokenizer(nextLine);
}
return tok.nextToken();
}
int readInt(){
return Integer.parseInt(readString());
}
long readLong(){
return Long.parseLong(readString());
}
double readDouble(){
return Double.parseDouble(readString());
}
}
| quadratic | 1179_B. Tolik and His Uncle | CODEFORCES |
import java.io.*;
import java.util.*;
public class Main {
static InputReader in = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
static long oo = 1000000000000L;
public static void main(String[] args) throws IOException {
int n = in.nextInt();
int q = in.nextInt();
ArrayDeque<Integer> dq = new ArrayDeque<>();
int max = -1;
for(int i = 0; i < n; ++i) {
int x = in.nextInt();
dq.add(x);
max = Math.max(max, x);
}
ArrayList<Pair> ans = new ArrayList<>();
while(dq.peekFirst() != max) {
int a = dq.pollFirst();
int b = dq.pollFirst();
ans.add(new Pair(a, b));
if(a > b) {
dq.addFirst(a);
dq.addLast(b);
}
else {
dq.addFirst(b);
dq.addLast(a);
}
}
ArrayList<Integer> a = new ArrayList<>();
dq.pollFirst();
for(int x : dq)
a.add(x);
while(q --> 0) {
long m = in.nextLong() - 1;
if(m < ans.size()) {
System.out.println(ans.get((int)m).first + " " + ans.get((int)m).second);
}
else {
int idx = (int)((m - ans.size()) % a.size());
System.out.println(max + " " + a.get(idx));
}
}
out.close();
}
static long lcm(long a, long b) {
return a * b / gcd(a, b);
}
static boolean nextPermutation(int[] a) {
for(int i = a.length - 2; i >= 0; --i) {
if(a[i] < a[i+1]) {
for(int j = a.length - 1; ; --j) {
if(a[i] < a[j]) {
int t = a[i];
a[i] = a[j];
a[j] = t;
for(i++, j = a.length - 1; i < j; ++i, --j) {
t = a[i];
a[i] = a[j];
a[j] = t;
}
return true;
}
}
}
}
return false;
}
static void shuffle(int[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
int t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static void shuffle(long[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
long t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static int lower_bound(int[] a, int n, int k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
static int lower_bound(long[] a, int n, long k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static class Pair implements Comparable<Pair> {
int first, second;
public Pair(int first, int second) {
super();
this.first = first;
this.second = second;
}
@Override
public int compareTo(Pair o) {
return this.first != o.first ? this.first - o.first : this.second - o.second;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + first;
result = prime * result + second;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
if (first != other.first)
return false;
if (second != other.second)
return false;
return true;
}
}
}
class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
} | linear | 1180_C. Valeriy and Deque | CODEFORCES |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class C {
void solve(){
int n = readInt();
int q = readInt();
int max = 0;
int[] a = new int[n];
Deque<Integer> deque = new ArrayDeque<>();
for(int i = 0;i<n;i++){
a[i] = readInt();
deque.addLast(a[i]);
max = Math.max(max, a[i]);
}
List<String> ans = new ArrayList<>();
while(deque.peekFirst() != max){
int one = deque.pollFirst();
int two = deque.pollFirst();
ans.add(one + " " + two);
deque.addFirst(one > two ? one : two);
deque.addLast(one > two ? two : one);
if(one == max) break;
}
for(int i = 0;i<n;i++){
a[i] = deque.pollFirst();
}
for(int i = 0;i<q;i++){
long x = readLong();
if(x <= ans.size()){
out.println(ans.get((int)x - 1));
continue;
}
x -= ans.size();
int y =(int) (x%(n - 1) - 1%(n - 1) + (n - 1)) % (n - 1) + 1;
out.println(max + " " + a[y]);
}
}
public static void main(String[] args) {
new C().run();
}
void run(){
init();
solve();
out.close();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init(){
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
String readLine(){
try{
return in.readLine();
}catch(Exception ex){
throw new RuntimeException(ex);
}
}
String readString(){
while(!tok.hasMoreTokens()){
String nextLine = readLine();
if(nextLine == null) return null;
tok = new StringTokenizer(nextLine);
}
return tok.nextToken();
}
int readInt(){
return Integer.parseInt(readString());
}
long readLong(){
return Long.parseLong(readString());
}
double readDouble(){
return Double.parseDouble(readString());
}
}
| linear | 1180_C. Valeriy and Deque | CODEFORCES |
import java.io.*;
import java.util.*;
public class CF1082D {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
int[] aa = new int[n];
int[] i1 = new int[n];
int[] i2 = new int[n];
int n1 = 0, n2 = 0, m2 = 0;
for (int i = 0; i < n; i++) {
int a = Integer.parseInt(st.nextToken());
aa[i] = a;
if (a == 1)
i1[n1++] = i;
else {
i2[n2++] = i;
m2 += a;
}
}
if (m2 < (n2 - 1) * 2 + n1) {
System.out.println("NO");
return;
}
int m = n2 - 1 + n1;
int d = n2 - 1 + Math.min(n1, 2);
PrintWriter pw = new PrintWriter(System.out);
pw.println("YES " + d);
pw.println(m);
for (int i = 0; i + 1 < n2; i++) {
pw.println((i2[i] + 1) + " " + (i2[i + 1] + 1));
aa[i2[i]]--; aa[i2[i + 1]]--;
}
if (n1 > 0) {
while (n2 > 0 && aa[i2[n2 - 1]] == 0)
n2--;
pw.println((i2[n2 - 1] + 1) + " " + (i1[n1 - 1] + 1));
aa[i2[n2 - 1]]--;
n1--;
}
for (int i = 0, j = 0; j < n1; j++) {
while (aa[i2[i]] == 0)
i++;
pw.println((i2[i] + 1) + " " + (i1[j] + 1));
aa[i2[i]]--;
}
pw.close();
}
}
| linear | 1082_D. Maximum Diameter Graph | CODEFORCES |
import java.io.IOException;
import java.io.InputStream;
import java.util.InputMismatchException;
import java.util.Stack;
public class D527A2 {
public static void main(String[] args) {
FastScanner in = new FastScanner(System.in);
int N = in.nextInt();
Stack<Integer> stack = new Stack<>();
for(int i = 0; i < N; i++) {
int num = in.nextInt() % 2;
if(stack.size() >= 1 && stack.lastElement() == num)
stack.pop();
else
stack.add(num);
}
System.out.println(stack.size() <= 1 ? "YES" : "NO");
}
/**
* Source: Matt Fontaine
*/
static class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int chars;
public FastScanner(InputStream stream) {
this.stream = stream;
}
int read() {
if (chars == -1)
throw new InputMismatchException();
if (curChar >= chars) {
curChar = 0;
try {
chars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (chars <= 0)
return -1;
}
return buf[curChar++];
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndline(c));
return res.toString();
}
}
}
/*
5
2 1 1 2 5
outputCopy
YES
inputCopy
3
4 5 3
outputCopy
YES
inputCopy
2
10 10
outputCopy
YES
inputCopy
3
1 2 3
outputCopy
NO
5
2 3 2 2 3
YES
*/ | linear | 1092_D1. Great Vova Wall (Version 1) | CODEFORCES |
import java.io.*;
import java.util.*;
public class tr {
static int[][] ad;
static boolean []vis;
static int []goods;
static int[][]sol;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n=sc.nextInt();
int []a=new int [n];
int max=0;
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
Stack<Integer> s=new Stack<>();
boolean f=true;
for(int i=0;i<n;i++) {
max=Math.max(max,a[i]);
if(!s.isEmpty() && a[i]>s.peek())
f=false;
s.push(a[i]);
while(!s.isEmpty()) {
int high=s.pop();
if(s.isEmpty() || s.peek()!=high) {
s.push(high);
break;
}
s.pop();
}
// System.out.println(s+" "+max);
}
//System.out.println(f+" "+max);
if(f && s.size()==0)
out.println("YES");
else if(f && s.size()==1 && s.peek()==max)
out.println("YES");
else
out.println("NO");
out.flush();
}
static int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
static class pair implements Comparable<pair> {
int a;
int b;
pair(int a, int b) {
this.a = a;
this.b = b;
}
public String toString() {
return a + " " + b;
}
@Override
public int compareTo(pair o) {
return o.a-a ;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
} | linear | 1092_D1. Great Vova Wall (Version 1) | CODEFORCES |
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Equator {
public static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static StringTokenizer st;
public static void main(String[] args) throws IOException {
int n = nextInt();
int[] a = intArray(n);
long s = 0;
for (int x : a)
s += x;
long m = 0;
for (int i = 0; i < n; i++) {
m += a[i];
if (m*2 >= s) {
System.out.println(i+1);
return;
}
}
}
public static String nextLine() throws IOException {
return in.readLine();
}
public static String nextString() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
public static int nextInt() throws IOException {
return Integer.parseInt(nextString());
}
public static long nextLong() throws IOException {
return Long.parseLong(nextString());
}
public static int[] intArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public static int[][] intArray(int n, int m) throws IOException {
int[][] a = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
a[i][j] = nextInt();
return a;
}
public static long[] longArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
} | linear | 962_A. Equator | CODEFORCES |
import java.io.*;
import java.util.*;
public class LectureSleep {
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public float nextFloat() {
return Float.parseFloat(next());
}
}
static InputReader r = new InputReader(System.in);
static PrintWriter pw = new PrintWriter(System.out);
public static void main(String[] args) {
int n = r.nextInt(); // duration of lecture
int k = r.nextInt(); // number of minutes keep mishka awake
int[] theorems = new int[n+1];
for(int i = 1; i <= n; i++){
theorems[i] = r.nextInt();
}
int[] mishka = new int[n+1];
for(int i = 1; i <= n; i++){
mishka[i] = r.nextInt();
}
int[] sums = new int[n+1];
for(int i = 1; i <= n; i++){
if(mishka[i] == 0){
sums[i] = sums[i-1] + theorems[i];
} else{
sums[i] = sums[i-1];
}
}
int max = 0;
for(int i = 1; i <= n-k+1; i++){
int sum = sums[i+k-1] - sums[i-1];
max = Math.max(max, sum);
}
int totalSum = 0;
for(int i = 1; i <= n; i++){
if(mishka[i] == 1){
totalSum += theorems[i];
}
}
pw.println(totalSum + max);
pw.close();
}
} | linear | 961_B. Lecture Sleep | CODEFORCES |
import java.io.*;
import java.util.StringTokenizer;
/**
* Created by IntelliJ IDEA.
* User: piyushd
* Date: Dec 5, 2010
* Time: 4:09:41 PM
* To change this template use File | Settings | File Templates.
*/
public class HamstersTigers {
private BufferedReader in;
private PrintWriter out;
private StringTokenizer st;
int solve(String a, int k){
int n = a.length(), ret = 0;
int temp[] = new int[n];
for(int i = 0; i < n; i++) temp[(n + i - k) % n] = (a.charAt(i) == 'T') ? 1: 0;
int left = 0, right = n - 1;
while(left < right){
while(temp[left] == 0) left++;
while(temp[right] == 1) right--;
if(left < right){
int t = temp[left];
temp[left] = temp[right];
temp[right] = t;
ret++;
}
}
return ret;
}
void solve() throws IOException {
int n = nextInt();
String a = next();
int ans = Integer.MAX_VALUE;
for(int fix = 0; fix < n; fix++){
ans = Math.min(ans, solve(a, fix));
}
out.println(ans);
}
HamstersTigers() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
//in = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C://Users/piyushd/Desktop/codeforces/sample.txt"))));
out = new PrintWriter(System.out);
eat("");
solve();
in.close();
out.close();
}
private void eat(String str) {
st = new StringTokenizer(str);
}
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 {
new HamstersTigers();
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
Scanner in;
PrintWriter out;
StreamTokenizer ST;
BufferedReader br;
int nextInt() throws IOException {
ST.nextToken();
return (int) ST.nval;
}
double nextDouble() throws IOException {
ST.nextToken();
return ST.nval;
}
String next() throws IOException {
ST.nextToken();
return ST.sval;
}
String nextLine() throws IOException {
return br.readLine();
}
void solve() throws IOException {
br.readLine();
char[]s = br.readLine().toCharArray();
int n = s.length;
int h=0;
for(int i=0;i<n;++i)if (s[i]=='H')++h;
int res=1000000;
for(int i=0;i<n;++i)
{
int t=0;
for(int j=0;j<h;++j)
{
if (s[(i+j)%n]=='T')++t;
}
res=Math.min(res,t);
}
out.println(res);
}
public void run() throws IOException {
// br = new BufferedReader(new FileReader(new File("input.txt")));
br = new BufferedReader(new InputStreamReader(System.in));
ST = new StreamTokenizer(br);
in = new Scanner(br);
out = new PrintWriter(System.out);
// out = new PrintWriter(new FileWriter(new File("output.txt")));
solve();
in.close();
out.close();
br.close();
}
public static void main(String[] args) throws Exception {
new Main().run();
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.io.FileNotFoundException;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Scanner;
public class Main
{
static final double eps=1e-10;
public static void main(String[] args) throws FileNotFoundException
{
new Main().solve();
}
public void solve() throws FileNotFoundException
{
Scanner cin=new Scanner(System.in);
int n;
n=cin.nextInt();
String s;
s=cin.next();
int ans=Integer.MAX_VALUE;
int h=0,t=0;
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)=='H')
h++;
else if(s.charAt(i)=='T')
t++;
}
ans=Math.min(ans,fun(s,'H',h));
ans=Math.min(ans,fun(s,'T',t));
System.out.println(ans);
}
public int fun(String s,char c,int num)
{
int ans=Integer.MAX_VALUE;
int ret=num;
for(int i=0;i<num;i++)
{
if(s.charAt(i)==c)
{
ret--;
}
}
ans=ret;
for(int i=0;i+num<s.length();i++)
{
if(s.charAt(i)!=c)
ret--;
if(s.charAt(i+num)!=c)
{
ret++;
}
ans=Math.min(ans, ret);
}
return ans;
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Stack;
import java.util.StringTokenizer;
public class Main {
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(inp);
boolean test = false;
String[] inData = { "9",
"HTHTHTHHT",
};
static int id = -1;
public String readLine() throws IOException {
id++;
if(test)
return inData[id];
else
return in.readLine();
}
public Main() throws Throwable {
int animalNr = Integer.valueOf(readLine());
String animals = readLine();
boolean[] state = new boolean[animalNr];
int tigerCount = 0;
for (int i = 0; i < animals.length(); i++) {
if('T' == animals.charAt(i)){
state[i] = true;
tigerCount++;
}
}
int best = Integer.MAX_VALUE;
for (int i = 0; i < state.length; i++) {
int swaps = 0;
for (int j = i; j < i+tigerCount; j++) {
if(state[j %animalNr] == false){
swaps ++;
}
}
if(swaps < best){
best = swaps;
}
}
System.out.println(best);
}
public static void main(String[] args) throws Throwable {
new Main();
}
} | linear | 46_C. Hamsters and Tigers | CODEFORCES |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.* ;
import java.io.* ;
import java.math.* ;
/************************
* *
* Lord Klotski *
* *
***********************/
public class C
{
static int[] arr ; static int L ;
public static void rotate()
{
int tmp = arr[0] ;
for (int i = 1 ; i < L ; i ++)
arr[i-1] = arr[i] ;
arr[L-1] = tmp ;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in) ;
L = input.nextInt() ; String s = input.next() ;
arr = new int[L]; for (int i = 0 ; i < L ; i ++) {arr[i] = s.charAt(i) == 'H' ? 1 : 0 ;}
// want to find longest sequence of 1s
// then rotate to head
int count = 99999 ;
for (int A = 0; A < L ; A ++)
{
int[] tmp = new int[L] ; System.arraycopy(arr, 0, tmp, 0, arr.length);
int ans = 0 ;
for (int i = 0 ; i < L ; i ++)
{
if (tmp[i] == 1) continue ;
for (int j = L-1 ; j > i ; j --)
{
if (tmp[j] == 0) continue ;
ans ++ ;
tmp[i] = 1 ; tmp[j] = 0 ;
//System.out.println("SWAP " + i + " " + j);
//for (int k = 0 ; k < L ; k ++)
// System.out.print(arr[k]);
//System.out.println("");
break;
}
}
count = Math.min(count,ans) ;
rotate() ;
}
// rotate until j is at the front
System.out.println(count);
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.util.*;
public class C {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
char[] s = new char[n];
String line = in.next();
int ct=0,ht=0;
for(int i=0;i<n;i++) //count animals
if(line.charAt(i)=='T')
ct++;
else
ht++;
int cnt = 1000000000;
int[] c = new int[2];
char[] cc = new char[2];
if(ct<ht)
{
c[0] = ct;
c[1] = ht;
cc[0] = 'T';
cc[1] = 'H';
}else{
c[0] = ht;
c[1] = ct;
cc[0] = 'H';
cc[1] = 'T';
}
for(int i=0;i<n;i++)
{
int ptr = i;
for(int j=0;j<c[0];j++) //fill First
{
s[ptr] = cc[0];
ptr = (ptr+1)%n;
}
for(int j=0;j<c[1];j++) //fill Second
{
s[ptr] = cc[1];
ptr = (ptr+1)%n;
}
//check
int ch = 0;
for(int j=0;j<n;j++) //difference
if(s[j]!=line.charAt(j)&&s[j]==cc[0])
ch++;
cnt = Math.min(cnt,ch);
}
System.out.print(cnt);
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
public class B {
private static StreamTokenizer in;
private static PrintWriter out;
private static int nextInt() throws Exception{
in.nextToken();
return (int)in.nval;
}
private static String nextString() throws Exception{
in.nextToken();
return in.sval;
}
static{
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
}
public static void main(String[] args)throws Exception{
int n = nextInt();
char[] c = nextString().toCharArray();
int tc = 0, hc = 0;
for(int i = 0;i<c.length; i++){
if(c[i] == 'T')tc++; else hc++;
}
// char g = 'T';
// if(tc > hc){
// tc = hc;
// g = 'H';
// }
int max = -1;
int pos = 0;
for(int i = 0; i<c.length; i++){
int a = 0;
for(int j = 0; j<tc;j++){
int k = i+j;
if(k>=n)k-=n;
if(c[k] == 'T'){
a++;
}
}
if(a>max){
max = a;
pos = i;
}
}
int min1 = tc - max;
max = -1;
pos = 0;
for(int i = 0; i<c.length; i++){
int a = 0;
for(int j = 0; j<hc;j++){
int k = i+j;
if(k>=n)k-=n;
if(c[k] == 'H'){
a++;
}
}
if(a>max){
max = a;
pos = i;
}
}
int min2 = hc - max;
out.println(Math.min(min1, min2));
out.flush();
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.util.Scanner;
public class Tsk1 {
static void metod() throws Exception {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String s = in.next();
String ss = s + s;
int t = 0;
for (int i = 0; i < n; i++) {
if (s.charAt(i) == 'T') {
t++;
}
}
if (t == 1 || t == n - 1) {
System.out.println(0);
} else {
int sum = 0;
for (int i = 0; i < t; i++) {
if (s.charAt(i) == 'T') {
sum++;
}
}
int max = sum;
for (int i = 0; i < s.length(); i++) {
if (ss.charAt(i) == 'T') {
if (ss.charAt(i + t) == 'H') {
sum--;
}
} else {
if (ss.charAt(i + t) == 'T') {
sum++;
max = Math.max(max, sum);
}
}
}
System.out.println(t - max);
}
}
public static void main(String[] args) throws Exception {
Tsk1.metod();
}
} | linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.util.*;
import java.io.*;
public class Solution {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(new InputStreamReader(System.in));
int n = sc.nextInt();
String s = sc.next();
sc.close();
int cH = 0;
for (int i=0; i < s.length(); i++)
if (s.charAt(i) == 'H')
cH++;
int best = cH;
for (int st=0; st < s.length(); st++) {
int cur = st;
int cnt = cH;
for (int i=0; i < cH; i++) {
if (s.charAt(cur) == 'H')
cnt--;
cur++;
if (cur == s.length()) cur = 0;
}
best = Math.min(best, cnt);
}
System.out.println(best);
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
/*
* Hello! You are trying to hack my solution, are you? =)
* Don't be afraid of the size, it's just a dump of useful methods like gcd, or n-th Fib number.
* And I'm just too lazy to create a new .java for every task.
* And if you were successful to hack my solution, please, send me this test as a message or to [email protected].
* It can help me improve my skills and i'd be very grateful for that.
* Sorry for time you spent reading this message. =)
* Good luck, unknown rival. =)
* */
import java.io.*;
import java.math.*;
import java.util.*;
public class Abra {
void solve() throws IOException {
int n = nextInt();
br.readLine();
int h = 0, t = 0;
String s = br.readLine();
for (int i = 0; i < n; i++) {
if ((char)s.charAt(i) == 'H') h++; else t++;
}
int m = 10001;
for (int j = 0; j < n; j++) {
int z = 0;
for (int i = 0; i < n; i++) {
if (i + 1 <= h) {
if (s.charAt((i + j) % n) != 'H') z++;
} else {
if (s.charAt((i + j) % n) != 'T') z++;
}
}
if (z < m) m = z;
}
out.println(m / 2);
}
public static void main(String[] args) throws IOException {
new Abra().run();
}
static class myLib {
long fact(long x) {
long a = 1;
for (long i = 2; i <= x; i++) {
a *= i;
}
return a;
}
long digitSum(String x) {
long a = 0;
for (int i = 0; i < x.length(); i++) {
a += x.charAt(i) - '0';
}
return a;
}
long digitSum(long x) {
long a = 0;
while (x > 0) {
a += x % 10;
x /= 10;
}
return a;
}
long digitMul(long x) {
long a = 1;
while (x > 0) {
a *= x % 10;
x /= 10;
}
return a;
}
int digitCubesSum(int x) {
int a = 0;
while (x > 0) {
a += (x % 10) * (x % 10) * (x % 10);
x /= 10;
}
return a;
}
double pif(double ax, double ay, double bx, double by) {
return Math.sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by));
}
double pif3D(double ax, double ay, double az, double bx, double by, double bz) {
return Math.sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by) + (az - bz) * (az - bz));
}
double pif3D(double[] a, double[] b) {
return Math.sqrt((a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]) + (a[2] - b[2]) * (a[2] - b[2]));
}
long gcd(long a, long b) {
if (a == 0 || b == 0) return 1;
if (a < b) {
long c = b;
b = a;
a = c;
}
while (a % b != 0) {
a = a % b;
if (a < b) {
long c = b;
b = a;
a = c;
}
}
return b;
}
int gcd(int a, int b) {
if (a == 0 || b == 0) return 1;
if (a < b) {
int c = b;
b = a;
a = c;
}
while (a % b != 0) {
a = a % b;
if (a < b) {
int c = b;
b = a;
a = c;
}
}
return b;
}
long lcm(long a, long b) throws IOException {
return a * b / gcd(a, b);
}
int lcm(int a, int b) throws IOException {
return a * b / gcd(a, b);
}
int countOccurences(String x, String y) {
int a = 0, i = 0;
while (true) {
i = y.indexOf(x);
if (i == -1) break;
a++;
y = y.substring(i + 1);
}
return a;
}
int[] findPrimes(int x) {
boolean[] forErato = new boolean[x - 1];
List<Integer> t = new Vector<Integer>();
int l = 0, j = 0;
for (int i = 2; i < x; i++) {
if (forErato[i - 2]) continue;
t.add(i);
l++;
j = i * 2;
while (j < x) {
forErato[j - 2] = true;
j += i;
}
}
int[] primes = new int[l];
Iterator<Integer> iterator = t.iterator();
for (int i = 0; iterator.hasNext(); i++) {
primes[i] = iterator.next().intValue();
}
return primes;
}
int rev(int x) {
int a = 0;
while (x > 0) {
a = a * 10 + x % 10;
x /= 10;
}
return a;
}
class myDate {
int d, m, y;
int[] ml = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
public myDate(int da, int ma, int ya) {
d = da;
m = ma;
y = ya;
if ((ma > 12 || ma < 1 || da > ml[ma - 1] || da < 1) && !(d == 29 && m == 2 && y % 4 == 0)) {
d = 1;
m = 1;
y = 9999999;
}
}
void incYear(int x) {
for (int i = 0; i < x; i++) {
y++;
if (m == 2 && d == 29) {
m = 3;
d = 1;
return;
}
if (m == 3 && d == 1) {
if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)) {
m = 2;
d = 29;
}
return;
}
}
}
boolean less(myDate x) {
if (y < x.y) return true;
if (y > x.y) return false;
if (m < x.m) return true;
if (m > x.m) return false;
if (d < x.d) return true;
if (d > x.d) return false;
return true;
}
void inc() {
if ((d == 31) && (m == 12)) {
y++;
d = 1;
m = 1;
} else {
if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)) {
ml[1] = 29;
}
if (d == ml[m - 1]) {
m++;
d = 1;
} else
d++;
}
}
}
int partition(int n, int l, int m) {// n - sum, l - length, m - every
// part
// <= m
if (n < l) return 0;
if (n < l + 2) return 1;
if (l == 1) return 1;
int c = 0;
for (int i = Math.min(n - l + 1, m); i >= (n + l - 1) / l; i--) {
c += partition(n - i, l - 1, i);
}
return c;
}
int rifmQuality(String a, String b) {
if (a.length() > b.length()) {
String c = a;
a = b;
b = c;
}
int c = 0, d = b.length() - a.length();
for (int i = a.length() - 1; i >= 0; i--) {
if (a.charAt(i) == b.charAt(i + d)) c++;
else
break;
}
return c;
}
String numSym = "0123456789ABCDEF";
String ZFromXToYNotation(int x, int y, String z) {
if (z.equals("0")) return "0";
String a = "";
// long q = 0, t = 1;
BigInteger q = BigInteger.ZERO, t = BigInteger.ONE;
for (int i = z.length() - 1; i >= 0; i--) {
q = q.add(t.multiply(BigInteger.valueOf(z.charAt(i) - 48)));
t = t.multiply(BigInteger.valueOf(x));
}
while (q.compareTo(BigInteger.ZERO) == 1) {
a = numSym.charAt((int) (q.mod(BigInteger.valueOf(y)).intValue())) + a;
q = q.divide(BigInteger.valueOf(y));
}
return a;
}
double angleFromXY(int x, int y) {
if ((x == 0) && (y > 0)) return Math.PI / 2;
if ((x == 0) && (y < 0)) return -Math.PI / 2;
if ((y == 0) && (x > 0)) return 0;
if ((y == 0) && (x < 0)) return Math.PI;
if (x > 0) return Math.atan((double) y / x);
else {
if (y > 0) return Math.atan((double) y / x) + Math.PI;
else
return Math.atan((double) y / x) - Math.PI;
}
}
static boolean isNumber(String x) {
try {
Integer.parseInt(x);
} catch (NumberFormatException ex) {
return false;
}
return true;
}
static boolean stringContainsOf(String x, String c) {
for (int i = 0; i < x.length(); i++) {
if (c.indexOf(x.charAt(i)) == -1) return false;
}
return true;
}
long pow(long a, long n) { // b > 0
if (n == 0) return 1;
long k = n, b = 1, c = a;
while (k != 0) {
if (k % 2 == 0) {
k /= 2;
c *= c;
} else {
k--;
b *= c;
}
}
return b;
}
int pow(int a, int n) { // b > 0
if (n == 0) return 1;
int k = n, b = 1, c = a;
while (k != 0) {
if (k % 2 == 0) {
k /= 2;
c *= c;
} else {
k--;
b *= c;
}
}
return b;
}
double pow(double a, int n) { // b > 0
if (n == 0) return 1;
double k = n, b = 1, c = a;
while (k != 0) {
if (k % 2 == 0) {
k /= 2;
c *= c;
} else {
k--;
b *= c;
}
}
return b;
}
double log2(double x) {
return Math.log(x) / Math.log(2);
}
int lpd(int[] primes, int x) {// least prime divisor
int i;
for (i = 0; primes[i] <= x / 2; i++) {
if (x % primes[i] == 0) {
return primes[i];
}
}
;
return x;
}
int np(int[] primes, int x) {// number of prime number
for (int i = 0; true; i++) {
if (primes[i] == x) return i;
}
}
int[] dijkstra(int[][] map, int n, int s) {
int[] p = new int[n];
boolean[] b = new boolean[n];
Arrays.fill(p, Integer.MAX_VALUE);
p[s] = 0;
b[s] = true;
for (int i = 0; i < n; i++) {
if (i != s) p[i] = map[s][i];
}
while (true) {
int m = Integer.MAX_VALUE, mi = -1;
for (int i = 0; i < n; i++) {
if (!b[i] && (p[i] < m)) {
mi = i;
m = p[i];
}
}
if (mi == -1) break;
b[mi] = true;
for (int i = 0; i < n; i++)
if (p[mi] + map[mi][i] < p[i]) p[i] = p[mi] + map[mi][i];
}
return p;
}
boolean isLatinChar(char x) {
if (((x >= 'a') && (x <= 'z')) || ((x >= 'A') && (x <= 'Z'))) return true;
else
return false;
}
boolean isBigLatinChar(char x) {
if (x >= 'A' && x <= 'Z') return true;
else
return false;
}
boolean isSmallLatinChar(char x) {
if (x >= 'a' && x <= 'z') return true;
else
return false;
}
boolean isDigitChar(char x) {
if (x >= '0' && x <= '9') return true;
else
return false;
}
class NotANumberException extends Exception {
private static final long serialVersionUID = 1L;
String mistake;
NotANumberException() {
mistake = "Unknown.";
}
NotANumberException(String message) {
mistake = message;
}
}
class Real {
String num = "0";
long exp = 0;
boolean pos = true;
long length() {
return num.length();
}
void check(String x) throws NotANumberException {
if (!stringContainsOf(x, "0123456789+-.eE")) throw new NotANumberException("Illegal character.");
long j = 0;
for (long i = 0; i < x.length(); i++) {
if ((x.charAt((int) i) == '-') || (x.charAt((int) i) == '+')) {
if (j == 0) j = 1;
else
if (j == 5) j = 6;
else
throw new NotANumberException("Unexpected sign.");
} else
if ("0123456789".indexOf(x.charAt((int) i)) != -1) {
if (j == 0) j = 2;
else
if (j == 1) j = 2;
else
if (j == 2)
;
else
if (j == 3) j = 4;
else
if (j == 4)
;
else
if (j == 5) j = 6;
else
if (j == 6)
;
else
throw new NotANumberException("Unexpected digit.");
} else
if (x.charAt((int) i) == '.') {
if (j == 0) j = 3;
else
if (j == 1) j = 3;
else
if (j == 2) j = 3;
else
throw new NotANumberException("Unexpected dot.");
} else
if ((x.charAt((int) i) == 'e') || (x.charAt((int) i) == 'E')) {
if (j == 2) j = 5;
else
if (j == 4) j = 5;
else
throw new NotANumberException("Unexpected exponent.");
} else
throw new NotANumberException("O_o.");
}
if ((j == 0) || (j == 1) || (j == 3) || (j == 5)) throw new NotANumberException("Unexpected end.");
}
public Real(String x) throws NotANumberException {
check(x);
if (x.charAt(0) == '-') pos = false;
long j = 0;
String e = "";
boolean epos = true;
for (long i = 0; i < x.length(); i++) {
if ("0123456789".indexOf(x.charAt((int) i)) != -1) {
if (j == 0) num += x.charAt((int) i);
if (j == 1) {
num += x.charAt((int) i);
exp--;
}
if (j == 2) e += x.charAt((int) i);
}
if (x.charAt((int) i) == '.') {
if (j == 0) j = 1;
}
if ((x.charAt((int) i) == 'e') || (x.charAt((int) i) == 'E')) {
j = 2;
if (x.charAt((int) (i + 1)) == '-') epos = false;
}
}
while ((num.length() > 1) && (num.charAt(0) == '0'))
num = num.substring(1);
while ((num.length() > 1) && (num.charAt(num.length() - 1) == '0')) {
num = num.substring(0, num.length() - 1);
exp++;
}
if (num.equals("0")) {
exp = 0;
pos = true;
return;
}
while ((e.length() > 1) && (e.charAt(0) == '0'))
e = e.substring(1);
try {
if (e != "") if (epos) exp += Long.parseLong(e);
else
exp -= Long.parseLong(e);
} catch (NumberFormatException exc) {
if (!epos) {
num = "0";
exp = 0;
pos = true;
} else {
throw new NotANumberException("Too long exponent");
}
}
}
public Real() {
}
String toString(long mantissa) {
String a = "", b = "";
if (exp >= 0) {
a = num;
if (!pos) a = '-' + a;
for (long i = 0; i < exp; i++)
a += '0';
for (long i = 0; i < mantissa; i++)
b += '0';
if (mantissa == 0) return a;
else
return a + "." + b;
} else {
if (exp + length() <= 0) {
a = "0";
if (mantissa == 0) {
return a;
}
if (mantissa < -(exp + length() - 1)) {
for (long i = 0; i < mantissa; i++)
b += '0';
return a + "." + b;
} else {
if (!pos) a = '-' + a;
for (long i = 0; i < mantissa; i++)
if (i < -(exp + length())) b += '0';
else
if (i + exp >= 0) b += '0';
else
b += num.charAt((int) (i + exp + length()));
return a + "." + b;
}
} else {
if (!pos) a = "-";
for (long i = 0; i < exp + length(); i++)
a += num.charAt((int) i);
if (mantissa == 0) return a;
for (long i = exp + length(); i < exp + length() + mantissa; i++)
if (i < length()) b += num.charAt((int) i);
else
b += '0';
return a + "." + b;
}
}
}
}
boolean containsRepeats(int... num) {
Set<Integer> s = new TreeSet<Integer>();
for (int d : num)
if (!s.contains(d)) s.add(d);
else
return true;
return false;
}
int[] rotateDice(int[] a, int n) {
int[] c = new int[6];
if (n == 0) {
c[0] = a[1];
c[1] = a[5];
c[2] = a[2];
c[3] = a[0];
c[4] = a[4];
c[5] = a[3];
}
if (n == 1) {
c[0] = a[2];
c[1] = a[1];
c[2] = a[5];
c[3] = a[3];
c[4] = a[0];
c[5] = a[4];
}
if (n == 2) {
c[0] = a[3];
c[1] = a[0];
c[2] = a[2];
c[3] = a[5];
c[4] = a[4];
c[5] = a[1];
}
if (n == 3) {
c[0] = a[4];
c[1] = a[1];
c[2] = a[0];
c[3] = a[3];
c[4] = a[5];
c[5] = a[2];
}
if (n == 4) {
c[0] = a[0];
c[1] = a[2];
c[2] = a[3];
c[3] = a[4];
c[4] = a[1];
c[5] = a[5];
}
if (n == 5) {
c[0] = a[0];
c[1] = a[4];
c[2] = a[1];
c[3] = a[2];
c[4] = a[3];
c[5] = a[5];
}
return c;
}
int min(int... a) {
int c = Integer.MAX_VALUE;
for (int d : a)
if (d < c) c = d;
return c;
}
int max(int... a) {
int c = Integer.MIN_VALUE;
for (int d : a)
if (d > c) c = d;
return c;
}
double maxD(double... a) {
double c = Double.MIN_VALUE;
for (double d : a)
if (d > c) c = d;
return c;
}
double minD(double... a) {
double c = Double.MAX_VALUE;
for (double d : a)
if (d < c) c = d;
return c;
}
int[] normalizeDice(int[] a) {
int[] c = a.clone();
if (c[0] != 0) if (c[1] == 0) c = rotateDice(c, 0);
else
if (c[2] == 0) c = rotateDice(c, 1);
else
if (c[3] == 0) c = rotateDice(c, 2);
else
if (c[4] == 0) c = rotateDice(c, 3);
else
if (c[5] == 0) c = rotateDice(rotateDice(c, 0), 0);
while (c[1] != min(c[1], c[2], c[3], c[4]))
c = rotateDice(c, 4);
return c;
}
boolean sameDice(int[] a, int[] b) {
for (int i = 0; i < 6; i++)
if (a[i] != b[i]) return false;
return true;
}
final double goldenRatio = (1 + Math.sqrt(5)) / 2;
final double aGoldenRatio = (1 - Math.sqrt(5)) / 2;
long Fib(int n) {
if (n < 0) if (n % 2 == 0) return -Math.round((pow(goldenRatio, -n) - pow(aGoldenRatio, -n)) / Math.sqrt(5));
else
return -Math.round((pow(goldenRatio, -n) - pow(aGoldenRatio, -n)) / Math.sqrt(5));
return Math.round((pow(goldenRatio, n) - pow(aGoldenRatio, n)) / Math.sqrt(5));
}
class japaneeseComparator implements Comparator<String> {
@Override
public int compare(String a, String b) {
int ai = 0, bi = 0;
boolean m = false, ns = false;
if (a.charAt(ai) <= '9' && a.charAt(ai) >= '0') {
if (b.charAt(bi) <= '9' && b.charAt(bi) >= '0') m = true;
else
return -1;
}
if (b.charAt(bi) <= '9' && b.charAt(bi) >= '0') {
if (a.charAt(ai) <= '9' && a.charAt(ai) >= '0') m = true;
else
return 1;
}
a += "!";
b += "!";
int na = 0, nb = 0;
while (true) {
if (a.charAt(ai) == '!') {
if (b.charAt(bi) == '!') break;
return -1;
}
if (b.charAt(bi) == '!') {
return 1;
}
if (m) {
int ab = -1, bb = -1;
while (a.charAt(ai) <= '9' && a.charAt(ai) >= '0') {
if (ab == -1) ab = ai;
ai++;
}
while (b.charAt(bi) <= '9' && b.charAt(bi) >= '0') {
if (bb == -1) bb = bi;
bi++;
}
m = !m;
if (ab == -1) {
if (bb == -1) continue;
else
return 1;
}
if (bb == -1) return -1;
while (a.charAt(ab) == '0' && ab + 1 != ai) {
ab++;
if (!ns) na++;
}
while (b.charAt(bb) == '0' && bb + 1 != bi) {
bb++;
if (!ns) nb++;
}
if (na != nb) ns = true;
if (ai - ab < bi - bb) return -1;
if (ai - ab > bi - bb) return 1;
for (int i = 0; i < ai - ab; i++) {
if (a.charAt(ab + i) < b.charAt(bb + i)) return -1;
if (a.charAt(ab + i) > b.charAt(bb + i)) return 1;
}
} else {
m = !m;
while (true) {
if (a.charAt(ai) <= 'z' && a.charAt(ai) >= 'a' && b.charAt(bi) <= 'z' && b.charAt(bi) >= 'a') {
if (a.charAt(ai) < b.charAt(bi)) return -1;
if (a.charAt(ai) > b.charAt(bi)) return 1;
ai++;
bi++;
} else
if (a.charAt(ai) <= 'z' && a.charAt(ai) >= 'a') return 1;
else
if (b.charAt(bi) <= 'z' && b.charAt(bi) >= 'a') return -1;
else
break;
}
}
}
if (na < nb) return 1;
if (na > nb) return -1;
return 0;
}
}
Random random = new Random();
}
void readIntArray(int[] a) throws IOException {
for (int i = 0; i < a.length; i++)
a[i] = nextInt();
}
String readChars(int l) throws IOException {
String r = "";
for (int i = 0; i < l; i++)
r += (char) br.read();
return r;
}
StreamTokenizer in;
PrintWriter out;
boolean oj;
BufferedReader br;
void init() throws IOException {
oj = System.getProperty("ONLINE_JUDGE") != null;
Reader reader = oj ? new InputStreamReader(System.in) : new FileReader("input.txt");
Writer writer = oj ? new OutputStreamWriter(System.out) : new FileWriter("output.txt");
br = new BufferedReader(reader);
in = new StreamTokenizer(br);
out = new PrintWriter(writer);
}
long selectionTime = 0;
void startSelection() {
selectionTime -= System.currentTimeMillis();
}
void stopSelection() {
selectionTime += System.currentTimeMillis();
}
void run() throws IOException {
long beginTime = System.currentTimeMillis();
long beginMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
init();
solve();
long endMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
long endTime = System.currentTimeMillis();
if (!oj) {
System.out.println("Memory used = " + (endMem - beginMem));
System.out.println("Total memory = " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));
System.out.println("Running time = " + (endTime - beginTime));
}
out.flush();
}
int nextInt() throws IOException {
in.nextToken();
return (int) in.nval;
}
long nextLong() throws IOException {
in.nextToken();
return (long) in.nval;
}
String nextString() throws IOException {
in.nextToken();
return in.sval;
}
double nextDouble() throws IOException {
in.nextToken();
return in.nval;
}
myLib lib = new myLib();
/*
* class cubeWithLetters { String consts = "ЧКТФЭЦ"; char[][] letters = { {
* 'А', 'Б', 'Г', 'В' }, { 'Д', 'Е', 'З', 'Ж' }, { 'И', 'Л', 'Н', 'М' }, {
* 'О', 'П', 'С', 'Р' }, { 'У', 'Х', 'Щ', 'Ш' }, { 'Ы', 'Ь', 'Я', 'Ю' } };
*
* char get(char x) { if (consts.indexOf(x) != -1) return x; for (int i = 0;
* i < 7; i++) { for (int j = 0; j < 4; j++) { if (letters[i][j] == x) { if
* (j == 0) return letters[i][3]; else return letters[i][j - 1]; } } }
* return '!'; }
*
* void subrotate(int x) { char t = letters[x][0]; letters[x][0] =
* letters[x][3]; letters[x][3] = letters[x][2]; letters[x][2] =
* letters[x][1]; letters[x][1] = t; }
*
* void rotate(int x) { subrotate(x); char t; if (x == 0) { t =
* letters[1][0]; letters[1][0] = letters[2][0]; letters[2][0] =
* letters[3][0]; letters[3][0] = letters[5][2]; letters[5][2] = t;
*
* t = letters[1][1]; letters[1][1] = letters[2][1]; letters[2][1] =
* letters[3][1]; letters[3][1] = letters[5][3]; letters[5][3] = t; } if (x
* == 1) { t = letters[2][0]; letters[2][0] = letters[0][0]; letters[0][0] =
* letters[5][0]; letters[5][0] = letters[4][0]; letters[4][0] = t;
*
* t = letters[2][3]; letters[2][3] = letters[0][3]; letters[0][3] =
* letters[5][3]; letters[5][3] = letters[4][3]; letters[4][3] = t; } if (x
* == 2) { t = letters[0][3]; letters[0][3] = letters[1][2]; letters[1][2] =
* letters[4][1]; letters[4][1] = letters[3][0]; letters[3][0] = t;
*
* t = letters[0][2]; letters[0][2] = letters[1][1]; letters[1][1] =
* letters[4][0]; letters[4][0] = letters[3][3]; letters[3][3] = t; } if (x
* == 3) { t = letters[2][1]; letters[2][1] = letters[4][1]; letters[4][1] =
* letters[5][1]; letters[5][1] = letters[0][1]; letters[0][1] = t;
*
* t = letters[2][2]; letters[2][2] = letters[4][2]; letters[4][2] =
* letters[5][2]; letters[5][2] = letters[0][2]; letters[0][2] = t; } if (x
* == 4) { t = letters[2][3]; letters[2][3] = letters[1][3]; letters[1][3] =
* letters[5][1]; letters[5][1] = letters[3][3]; letters[3][3] = t;
*
* t = letters[2][2]; letters[2][2] = letters[1][2]; letters[1][2] =
* letters[5][0]; letters[5][0] = letters[3][2]; letters[3][2] = t; } if (x
* == 5) { t = letters[4][3]; letters[4][3] = letters[1][0]; letters[1][0] =
* letters[0][1]; letters[0][1] = letters[3][2]; letters[3][2] = t;
*
* t = letters[4][2]; letters[4][2] = letters[1][3]; letters[1][3] =
* letters[0][0]; letters[0][0] = letters[3][1]; letters[3][1] = t; } }
*
* public String toString(){ return " " + letters[0][0] + letters[0][1] +
* "\n" + " " + letters[0][3] + letters[0][2] + "\n" + letters[1][0] +
* letters[1][1] + letters[2][0] + letters[2][1] + letters[3][0] +
* letters[3][1] + "\n" + letters[1][3] + letters[1][2] + letters[2][3] +
* letters[2][2] + letters[3][3] + letters[3][2] + "\n" + " " +
* letters[4][0] + letters[4][1] + "\n" + " " + letters[4][3] +
* letters[4][2] + "\n" + " " + letters[5][0] + letters[5][1] + "\n" + " "
* + letters[5][3] + letters[5][2] + "\n"; } }
*
*
* Vector<Integer>[] a; int n, mc, c1, c2; int[] col;
*
* void wave(int x, int p) { for (Iterator<Integer> i = a[x].iterator();
* i.hasNext(); ) { int t = i.next(); if (t == x || t == p) continue; if
* (col[t] == 0) { col[t] = mc; wave(t, x); } else { c1 = x; c2 = t; } } }
*
* void solve() throws IOException {
*
* String s = "ЕПОЕЬРИТСГХЖЗТЯПСТАПДСБИСТЧК"; //String s =
* "ЗЬУОЫТВЗТЯПУБОЫТЕАЫШХЯАТЧК"; cubeWithLetters cube = new
* cubeWithLetters(); for (int x = 0; x < 4; x++) { for (int y = x + 1; y <
* 5; y++) { for (int z = y + 1; z < 6; z++) { cube = new cubeWithLetters();
* out.println(cube.toString()); cube.rotate(x);
* out.println(cube.toString()); cube.rotate(y);
* out.println(cube.toString()); cube.rotate(z);
* out.println(cube.toString()); out.print(x + " " + y + " " + z + " = ");
* for (int i = 0; i < s.length(); i++) { out.print(cube.get(s.charAt(i)));
* } out.println(); } } }
*
* int a = nextInt(), b = nextInt(), x = nextInt(), y = nextInt();
* out.print((lib.min(a / (x / lib.gcd(x, y)), b / (y / lib.gcd(x, y))) * (x
* / lib.gcd(x, y))) + " " + (lib.min(a / (x / lib.gcd(x, y)), b / (y /
* lib.gcd(x, y))) * (y / lib.gcd(x, y)))); }
*/
} | linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.util.Scanner;
public class C {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int len = s.nextInt();
s.nextLine();
String l = s.nextLine();
char[] ca = l.toCharArray();
int h = 0;
for (char c : ca)
h += A(c);
int cur = h;
int i;
for (i = 0; i < h; i++)
cur -= A(ca[i]);
int best = cur;
while (i != h + len) {
cur -= A(ca[i % len]);
cur += A(ca[(i - h) % len]);
best = best > cur ? cur : best;
i++;
}
System.out.println(best);
}
public static int A(char x) {
return x == 'H' ? 1 : 0;
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Homyak implements Runnable {
private void solve() throws IOException {
int n = nextInt();
String seq = nextToken();
int nh = 0;
int nt = 0;
for (int i = 0; i < n; ++i)
if (seq.charAt(i) == 'H')
++nh;
else
++nt;
int res = n;
for (int delta = 0; delta < n; ++delta) {
int changed = 0;
int at = delta;
for (int i = 0; i < nh; ++i) {
if (seq.charAt(at) != 'H')
++changed;
++at;
if (at >= n)
at = 0;
}
for (int i = 0; i < nt; ++i) {
if (seq.charAt(at) != 'T')
++changed;
++at;
if (at >= n)
at = 0;
}
res = Math.min(res, changed / 2);
}
writer.println(res);
}
public static void main(String[] args) {
new Homyak().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
} | linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.io.*;
import java.util.*;
public class C
{
String line;
StringTokenizer inputParser;
BufferedReader is;
FileInputStream fstream;
DataInputStream in;
void openInput(String file)
{
if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin
else
{
try{
fstream = new FileInputStream(file);
in = new DataInputStream(fstream);
is = new BufferedReader(new InputStreamReader(in));
}catch(Exception e)
{
System.err.println(e);
}
}
}
void readNextLine()
{
try {
line = is.readLine();
inputParser = new StringTokenizer(line, " ");
//System.err.println("Input: " + line);
} catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
}
int NextInt()
{
String n = inputParser.nextToken();
int val = Integer.parseInt(n);
//System.out.println("I read this number: " + val);
return val;
}
String NextString()
{
String n = inputParser.nextToken();
return n;
}
void closeInput()
{
try {
is.close();
} catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
}
public static void main(String [] argv)
{
String filePath=null;
if(argv.length>0)filePath=argv[0];
C c = new C(filePath);
}
public C(String inputFile)
{
openInput(inputFile);
readNextLine();
int N=NextInt();
boolean [] p = new boolean[N];
readNextLine();
int h=0;
for(int i=0; i<N; i++)
{
p[i]=line.charAt(i)=='H';
if(p[i])h++;
}
int ret=N;
for(int i=0; i<N; i++)
{
int m=0;
for(int j=i; j<i+h; j++)
{
int n=j%N;
if(!p[n])m++;
}
ret=Math.min(ret, m);
}
System.out.println(ret);
closeInput();
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.io.*;
import java.util.*;
public class Main implements Runnable {
public void _main() throws IOException {
int n = nextInt();
int[] a = new int[n];
String s = next();
for (int i = 0; i < n; i++)
a[i] = s.charAt(i) == 'H' ? 1 : 0;
int res = 10 * n;
for (int i = 0; i < n; i++) {
int[] b = new int[n];
for (int j = 0; j < n; j++)
b[j] = a[(i + j) % n];
res = Math.min(res, solve(b, 0));
res = Math.min(res, solve(b, 1));
}
out.print(res);
}
private int solve(int[] a, int x) {
int n = a.length;
int j;
for (j = n - 1; j >= 0; j--)
if (a[j] == x)
break;
if (a[j] != x) return 0;
int res = 0;
for (int i = 0; i < j; i++)
if (a[i] != x) {
--j;
while (j >= i && a[j] != x)
--j;
++res;
}
return res;
}
private BufferedReader in;
private PrintWriter out;
private StringTokenizer st;
private String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String rl = in.readLine();
if (rl == null)
return null;
st = new StringTokenizer(rl);
}
return st.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(next());
}
private long nextLong() throws IOException {
return Long.parseLong(next());
}
private double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public static void main(String[] args) {
Locale.setDefault(Locale.UK);
new Thread(new Main()).start();
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
_main();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(202);
}
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.io.*;
import java.math.*;
import java.util.*;
public class Solution {
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) throws Exception{
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int)in.nval;
in.nextToken();
String st = in.sval;
char[] a = new char[n];
for (int i = 0; i<n; i++)
a[i] = st.charAt(i);
int kH = 0;
int kT = 0;
for (int i =0; i<n; i++)
if (a[i] == 'T') kT++;
else kH++;
int kol = 0;
int min = Integer.MAX_VALUE;
int poz;
for (int i=0; i<n; i++)
{
kol = 0;
if (a[i] == 'T') {
for (int j = 0; j<kT; j++){
poz = (i+j)%n;
if (a[poz] == 'H') kol++;
}
if (kol < min) min = kol;
}
else {
for (int j = 0; j<kH; j++){
poz = (i+j)%n;
if (a[poz] == 'T') kol++;
}
if (kol < min) min = kol;
}
}
out.print(min);
out.flush();
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.io.*;
import java.util.*;
public class C {
MyScanner in;
PrintWriter out;
public static void main(String[] args) throws Exception {
new C().run();
}
public void run() throws Exception {
in = new MyScanner();
out = new PrintWriter(System.out);
solve();
out.close();
}
public void solve() throws Exception {
int n = in.nextInt();
char[] a = in.next().toCharArray();
int h = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] == 'H') h++;
}
char[] b = new char[2 * a.length - 1];
for (int i = 0; i < b.length; i++) {
b[i] = a[i % a.length];
}
int maxh = 0;
int hh = 0;
for (int i = 0; i < b.length - h; i++) {
hh = 0;
for (int j = 0; j < h; j++) {
if (b[i + j] == 'H') hh++;
}
maxh = Math.max(maxh, hh);
}
/*for (int i = 0; i < b.length; i++) {
out.print(b[i]);
}
out.println();*/
//out.println(h + " " + maxh);
out.println(h - maxh);
}
class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() throws Exception {
if ((st == null) || (!st.hasMoreTokens())) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
int nextInt() throws Exception {
return Integer.parseInt(next());
}
double nextDouble() throws Exception {
return Double.parseDouble(next());
}
boolean nextBoolean() throws Exception {
return Boolean.parseBoolean(next());
}
long nextLong() throws Exception {
return Long.parseLong(next());
}
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
public class Main {
public static StreamTokenizer in;
public static PrintStream out;
public static BufferedReader br;
public static String readString() throws IOException {
in.nextToken();
return in.sval;
}
public static double readDouble() throws IOException {
in.nextToken();
return in.nval;
}
public static int readInt() throws IOException {
in.nextToken();
return (int) in.nval;
}
public static String readLine() throws IOException {
return br.readLine();
}
public static int genans(String ss) {
int n = ss.length();
char[] s = ss.toCharArray();
int res = 0;
while (true) {
int firstT = -1;
for (int i=0; i<n; i++)
if (s[i]=='T') { firstT = i; break; }
int lastH = -1;
for (int i=n-1; i>=0; i--)
if (s[i]=='H') { lastH=i; break; }
if (firstT<lastH) {
res++;
s[firstT] = 'H';
s[lastH] = 'T';
} else break;
}
return res;
}
public static void main(String[] args) throws IOException {
in = new StreamTokenizer(new InputStreamReader (System.in) );
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintStream(System.out);
readLine();
String s = readLine();
int n = s.length();
String kk = s;
int ans = n*100;
for (int tr=0; tr<n+2; tr++) {
String kk2 = "";
for (int i=1; i<n; i++) kk2 = kk2 +kk.charAt(i);
kk2 = kk2 + kk.charAt(0);
kk = kk2;
int cur = genans(kk);
//out.println(kk+" "+cur);
if (cur<ans) ans = cur;
}
out.println(ans);
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.util.*;
import java.io.*;
import static java.util.Arrays.*;
import static java.lang.Math.*;
import java.math.*;
public class Main {
void run() throws IOException {
int n = nint();
char[] s = token().toCharArray();
int h = 0;
for (int i = 0; i < n; i++) {
if (s[i] == 'H') h++;
}
int r = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
int t = 0;
for (int j = i; j < i + h; j++) {
if (s[j % n] == 'T') t++;
}
r = min(r, t);
}
out.println(r);
}
class pair implements Comparable <pair> {
int x, y;
pair(int x, int y) {
this.x = x;
this.y = y;
}
public int compareTo (pair p) {
if (x != p.x) {
return x - p.x;
} else {
return y - p.y;
}
}
}
// static PrintWriter out;
// static Scanner in;
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.US);
//final String FILENAME = "jury"; in = new Scanner (new File (FILENAME + ".in")); out = new PrintWriter (new File(FILENAME + ".out"));
// in = new Scanner (System.in); out = new PrintWriter (System.out);
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
st = new StringTokenizer(" ");
new Main().run();
/*out = new PrintWriter (System.out);
final int NUMBER_OF_TESTS = 35;
for (int i = 1; i <= NUMBER_OF_TESTS; i++) {
Scanner test = new Scanner (new File ("tests/" + i + ".in"));
Scanner right = new Scanner (new File ("tests/" + i + ".out"));
String get_right = right.nextLine();
String get_test = new Main().run(test);
if (get_right.equals(get_test)) {
out.println("Test #" + i + ": " + "OK!");
} else {
out.println("Test #" + i + ": " + "ERROR!");
out.println("Expected: " + get_right);
out.println("Received: " + get_test);
break;
}
}*/
out.close();
}
static BufferedReader in;
static PrintWriter out;
static StringTokenizer st;
String token() throws IOException {
while (!st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int nint() throws IOException {
return Integer.parseInt(token());
}
long nlong() throws IOException {
return Long.parseLong(token());
}
double ndouble() throws IOException {
return Double.parseDouble(token());
}
} | linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
public class C43 {
static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static PrintWriter out = new PrintWriter(System.out);
static int nextInt() throws IOException {
in.nextToken();
return Integer.valueOf(in.sval);
}
static double nextDouble() throws IOException {
in.nextToken();
return Double.valueOf(in.sval);
}
static String nextString() throws IOException {
in.nextToken();
return in.sval;
}
static {
in.ordinaryChars('0', '9');
in.wordChars('0', '9');
in.ordinaryChars('.', '.');
in.wordChars('.', '.');
in.ordinaryChars('-', '-');
in.wordChars('-', '-');
}
public static void main(String[] args) throws IOException {
int n = nextInt();
char[] s = nextString().toCharArray();
int h = 0;
for (int i = 0; i < n; i++)
if (s[i] == 'H')
h++;
int ans = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
int p = i, t = 0;
for (int j = 0; j < h; j++, p = (p+1)%n)
if (s[p] == 'T')
t++;
ans = Math.min(ans, t);
}
out.println(ans);
out.flush();
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.util.*;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner cin = new Scanner(System.in);
int n;
n = cin.nextInt();
String s = cin.next();
int ans = n;
int cntH = 0,cntT = 0;
for(int i=0;i<n;i++)
{
if(s.charAt(i)=='H')cntH++;
}
cntT = n - cntH;
for(int i=0;i+cntH<n;i++)
{
int tmp = 0;
for(int j=i;j<i+cntH;j++)
if(s.charAt(j)=='T')tmp++;
if(ans>tmp)ans = tmp;
}
for(int i=0;i+cntT<n;i++)
{
int tmp = 0;
for(int j=i;j<i+cntT;j++)
if(s.charAt(j)=='H')tmp++;
if(ans>tmp)ans = tmp;
}
System.out.println(ans);
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.io.*;
import java.math.BigInteger;
import java.util.StringTokenizer;
public class C implements Runnable {
private static final boolean USE_FILE_IO = false;
private static final String FILE_IN = "c.in";
private static final String FILE_OUT = "c.out";
BufferedReader in;
PrintWriter out;
StringTokenizer tokenizer = new StringTokenizer("");
public static void main(String[] args) {
new Thread(new C()).start();
}
int n, h, t;
char[] c;
private void solve() throws IOException {
n = nextInt();
c = nextToken().toCharArray();
if (c.length != n) {
throw new IllegalStateException();
}
for (char l : c)
if (l == 'H') {
h++;
}
t = n - h;
if (h == 0) {
out.print(0);
return;
}
int answer = Integer.MAX_VALUE;
for (int hLo = 0; hLo < n; hLo++)
if (c[hLo] == 'H') {
int hHi = (hLo + h) % n;
int current = 0;
int j = hLo;
while (j != hHi) {
if (c[j] == 'T') {
current++;
}
j = (j + 1) % n;
}
answer = Math.min(answer, current);
}
out.print(answer);
}
public void run() {
long timeStart = System.currentTimeMillis();
try {
if (USE_FILE_IO) {
in = new BufferedReader(new FileReader(FILE_IN));
out = new PrintWriter(new FileWriter(FILE_OUT));
} else {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
}
solve();
in.close();
out.close();
} catch (IOException e) {
throw new IllegalStateException(e);
}
long timeEnd = System.currentTimeMillis();
System.out.println("Time spent: " + (timeEnd - timeStart) + " ms");
}
private String nextToken() throws IOException {
while (!tokenizer.hasMoreTokens()) {
String line = in.readLine();
if (line == null) {
return null;
}
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private BigInteger nextBigInt() throws IOException {
return new BigInteger(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
} | linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.io.*;
import java.util.*;
public class Main {
private static boolean _READ_FROM_FILE = System.getProperty("ONLINE_JUDGE") == null;
private static Scanner in;
private static void core() {
int n = in.nextInt();
ArrayList<Character> all = new ArrayList<Character>();
for (char ch : in.next().toCharArray()) {
all.add(ch);
}
int res = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
int now = calc(all);
res = Math.min(res, now);
all.add(all.get(0));
all.remove(0);
}
System.out.println(res);
}
private static int calc(ArrayList<Character> all) {
int nh = 0;
for (char ch: all) {
if (ch == 'H')
++nh;
}
int r1 = 0;
for (int i = 0; i < nh; i++) {
if (all.get(i) != 'H')
++r1;
}
int nt = all.size() - nh;
int r2 = 0;
for (int i = 0; i < nt; i++) {
if (all.get(i) != 'T')
++r2;
}
return Math.min(r1, r2);
}
static void debug(Object...os) {
System.out.println(Arrays.deepToString(os));
}
public static void main(String[] args) throws FileNotFoundException {
if (_READ_FROM_FILE)
System.setIn(new FileInputStream("in.in"));
in = new Scanner(System.in);
core();
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.io.*;
import java.util.*;
public class Solution {
StreamTokenizer in;
PrintWriter out;
public static void main(String[] args) throws Exception {
new Solution().run();
}
public void run() throws Exception {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter (new OutputStreamWriter(System.out));
solve();
out.flush();
}
int nextInt() throws Exception {
in.nextToken();
return (int) in.nval;
}
String next() throws Exception {
in.nextToken();
return in.sval;
}
public void solve() throws Exception {
int n=nextInt();
String s=next();
String ss = s + s;
int t = 0;
for (int i = 0; i < n; i++) {
if (s.charAt(i) == 'T') {
t++;
}
}
if (t == 1 || t == n - 1) {
out.println(0);
} else {
int sum = 0;
for (int i = 0; i < t; i++) {
if (s.charAt(i) == 'T') {
sum++;
}
}
int max = sum;
for (int i = 0; i < s.length(); i++) {
if (ss.charAt(i) == 'T') {
if (ss.charAt(i + t) == 'H') {
sum--;
}
} else {
if (ss.charAt(i + t) == 'T') {
sum++;
max = Math.max(max, sum);
}
}
}
out.println(t - max);
}
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
/*
* Author: Nikhil Garg
* Date: 2010-12-05
*
*/
import java.io.*;
import java.util.*;
import java.math.*;
public class javatemp
{
static String map(int a)
{
if( a == 0) return "S";
else if ( a == 1 ) return "M";
else if ( a == 2 ) return "L";
else if ( a == 3 ) return "XL";
else if ( a == 4 ) return "XXL";
return "";
}
public static void main(String[] args) throws IOException
{
BufferedReader in = new BufferedReader( new InputStreamReader(System.in));
int ans = 1000;
in.readLine();
String s = in.readLine();
int H = 0;
for(int i =0; i < s.length(); i++)
if( s.charAt(i) == 'H') H++;
for(int i = 0; i < s.length(); i++)
{
int count = 0;
for(int j = 0; j < H; j++)
if( s.charAt( (i +j) % s.length()) =='T') count ++;
ans = Math.min ( ans, count);
}
System.out.println(ans);
}
static void debug(Object...os)
{
System.out.println(Arrays.deepToString(os));
}
} | linear | 46_C. Hamsters and Tigers | CODEFORCES |
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 {
public static void main(String[] args) throws IOException {
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) {}
new Main().run();
} catch (IOException e) {
e.printStackTrace();
}
}
}, "1", 1L << 24).start();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
int N;
int[] a;
int[] b;
int[] c;
int T, H;
void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
N = nextInt();
char[] s = nextToken().toCharArray();
a = new int [N];
H = 0;
T = 0;
for (int i = 0; i < s.length; i++) {
a[i] = s[i] == 'T' ? 1 : 0;
if (s[i] == 'T')
T++;
else
H++;
}
if (T == 1 || H == 1) {
out.println(0);
out.close();
return;
}
b = Arrays.copyOf(a, a.length);
c = Arrays.copyOf(a, a.length);
sort(c);
int ans = 100000000;
for (int o = 0; o < N; o++) {
for (int i = 0; i < N; i++)
b[(i + o) % N] = a[i];
int cur = 0;
for (int i = 0; i < N; i++)
if (b[i] != c[i])
cur++;
ans = min(ans, cur / 2);
}
out.println(ans);
out.close();
}
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());
}
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;
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class C43 implements Runnable {
public Scanner in;
public PrintWriter out;
final static String TASK_NAME = "";
C43() throws IOException {
in = new Scanner( System.in );
// in = new StreamTokenizer( new InputStreamReader( System.in ) );
out = new PrintWriter( System.out );
}
void close() throws IOException {
out.close();
}
public void run() {
try {
solve();
close();
} catch ( Exception e ) {
e.printStackTrace();
}
}
public void solve() throws IOException {
int n = in.nextInt();
char[] c = in.next().toCharArray();
int t = 0;
for ( int i = 0; i < n; i ++ ) {
if ( c[i] == 'T' ) {
t ++;
}
}
int ct = 0;
for ( int i = 0; i < t; i ++ ) {
if ( c[i] == 'T' ) {
ct ++;
}
}
int r = 0;
for ( int i = 0; i < n; i ++ ) {
r = Math.max( r, ct );
if ( c[i] == 'T' ) {
ct --;
}
if ( c[( i + t ) % n] == 'T' ) {
ct ++;
}
}
out.println( t - r );
}
public static void main( String[] args ) throws IOException {
new Thread( new C43() ).start();
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
//package round43;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class C {
Scanner in;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
char[] x = in.next().toCharArray();
int t = 0;
for(int i = 0;i < n;i++){
if(x[i] == 'T'){
t++;
}
}
int min = 9999;
for(int i = 0;i < n;i++){
int y = 0;
for(int j = i;j < i + t;j++){
if(x[j % n] == 'T'){
y++;
}
}
min = Math.min(min, t - y);
}
out.println(min);
}
void run() throws Exception
{
in = INPUT.isEmpty() ? new Scanner(System.in) : new Scanner(INPUT);
out = new PrintWriter(System.out);
solve();
out.flush();
}
public static void main(String[] args) throws Exception
{
new C().run();
}
int ni() { return Integer.parseInt(in.next()); }
void tr(Object... o) { if(INPUT.length() != 0)System.out.println(o.length > 1 || o[0].getClass().isArray() ? Arrays.deepToString(o) : o[0]); }
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.io.*;
import java.util.*;
public class Solution {
static BufferedReader br=null;
static PrintWriter pw=null;
static StringTokenizer st=null;
static String FILENAME="";
void nline(){
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
int ni(){
while(st==null || !st.hasMoreTokens()) nline();
return Integer.parseInt(st.nextToken());
}
long nl(){
while(st==null || !st.hasMoreTokens()) nline();
return Long.parseLong(st.nextToken());
}
double nd(){
while(st==null || !st.hasMoreTokens()) nline();
return Double.parseDouble(st.nextToken());
}
String ns(){
while(st==null || !st.hasMoreTokens()) nline();
return st.nextToken();
}
String nstr(){
String s="";
try {
s=br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
public void solve(){
int n = ni();
String s = nstr();
int[] a = new int[n];
for (int i=0;i<n;i++)
a[i]=s.charAt(i)=='H'?0:1;
int hc = 0;
for (int i=0;i<n;i++)
if (a[i]==0) hc++;
int min = 1000000;
for (int ss=0;ss<n;ss++) {
int rc = 0;
for (int i=0;i<hc;i++)
if (a[(i+ss)%n]==0) rc++;
if (hc-rc<min) min=hc-rc;
}
pw.print(min);
}
public void run(){
solve();
pw.close();
}
public static void main(String[] args) {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(System.out);
new Solution().run();
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.io.BufferedInputStream;
import java.util.Scanner;
public class HamstersAndTigers { //Round #XX - Hamsters and Tigers
public static void main(String[] args) {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
int numAnimals = sc.nextInt();
String positions = sc.next();
int numTigers = 0;
int numHamsters = 0;
for(int i = 0; i < positions.length(); i++) {
if(positions.charAt(i) == 'T') {
numTigers++;
} else {
numHamsters++;
}
}
int minDifference = Integer.MAX_VALUE;
StringBuilder tigerChars = new StringBuilder(1000);
StringBuilder hamsterChars = new StringBuilder(1000);
for(int i = 0; i < numHamsters; i++) {
hamsterChars.append('H');
}
StringBuilder remainingTigerChars = new StringBuilder(1000);
for(int i = 0; i < numTigers; i++) {
remainingTigerChars.append('T');
}
for(int i = 0; i <= numTigers; i++) {
StringBuilder generated = new StringBuilder();
generated.append(tigerChars);
generated.append(hamsterChars);
generated.append(remainingTigerChars);
//System.out.println(generated);
if(remainingTigerChars.length() >= 1) {
remainingTigerChars.deleteCharAt(remainingTigerChars.length() - 1);
}
tigerChars.append('T');
int diffCount = stringDiffCount(positions, generated.toString());
if(diffCount < minDifference) {
minDifference = diffCount;
}
}
//System.out.println("");
hamsterChars = new StringBuilder(1000);
tigerChars = new StringBuilder(1000);
for(int i = 0; i < numTigers; i++) {
tigerChars.append('T');
}
StringBuilder remainingHamsterChars = new StringBuilder(1000);
for(int i = 0; i < numHamsters; i++) {
remainingHamsterChars.append('H');
}
for(int i = 0; i <= numHamsters; i++) {
StringBuilder generated = new StringBuilder();
generated.append(hamsterChars);
generated.append(tigerChars);
generated.append(remainingHamsterChars);
//System.out.println(generated);
if(remainingHamsterChars.length() >= 1) {
remainingHamsterChars.deleteCharAt(remainingHamsterChars.length() - 1);
}
hamsterChars.append('H');
int diffCount = stringDiffCount(positions, generated.toString());
if(diffCount < minDifference) {
minDifference = diffCount;
}
}
System.out.println(minDifference / 2);
}
private static int stringDiffCount(String strOne, String strTwo) {
int diffCount = 0;
for(int i = 0; i < strOne.length(); i++) {
if(strOne.charAt(i) != strTwo.charAt(i)) {
diffCount++;
}
}
return diffCount;
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int[] a=new int[1010];
while(in.hasNext()){
int n=in.nextInt();
String s=in.next();
int sum=0;
for(int i=0;i<n;++i){
if(s.charAt(i)=='H'){
a[i]=1;
++sum;
}
else a[i]=0;
}
int min=10010;
for(int i=0;i<n-sum;++i){
int count=0;
for(int j=i+sum;j<n;++j){
if(a[j]==1)++count;
}
for(int j=0;j<i;++j){
if(a[j]==1)++count;
}
if(count<min)min=count;
}
sum=n-sum;
for(int i=0;i<n-sum;++i){
int count=0;
for(int j=i+sum;j<n;++j){
if(a[j]==0)++count;
}
for(int j=0;j<i;++j){
if(a[j]==0)++count;
}
if(count<min)min=count;
}
System.out.println(min);
}
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.util.Scanner;
public class ProblemC {
public static void main(String[] args) {
ProblemC problem = new ProblemC();
problem.solve();
}
private void solve() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String s = sc.next();
int ret = n;
int toth = 0;
int tott = 0;
for (int j = 0; j < n; j++) {
if (s.charAt(j) == 'H') {
toth++;
} else {
tott++;
}
}
for (int j = 0; j < n; j++) {
int cnth = 0;
for (int k = 0; k < toth; k++) {
int pos = (j + k) % n;
if (s.charAt(pos) == 'H') {
cnth++;
}
}
int makeh = toth - cnth;
ret = Math.min(ret, makeh);
}
System.out.println(ret);
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.util.*;
import java.math.*;
import static java.lang.Character.isDigit;
import static java.lang.Character.isLowerCase;
import static java.lang.Character.isUpperCase;
import static java.lang.Math.*;
import static java.math.BigInteger.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
import static java.lang.Character.isDigit;
public class Main{
public static void main(String[] args) {
new Main().run();
}
Scanner sc=new Scanner(System.in);
void run() {
int n=sc.nextInt();
char[] cs=sc.next().toCharArray();
int h=0;
for(int i=0;i<n;i++)if(cs[i]=='H')h++;
int res=n;
for(int i=0;i<n;i++) {
int val=0;
for(int j=0;j<h;j++)if(cs[(i+j)%n]=='T')val++;
res=min(res,val);
}
System.out.println(res);
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import com.sun.org.apache.xpath.internal.axes.SubContextList;
import java.util.Scanner;
/**
*
* @author Madi
*/
public class Round42CC {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
String s = sc.nextLine();
int k = 0;
for (int i = 0; i < n; i++) {
if (s.charAt(i) == 'H') {
k++;
}
}
s = s + s.substring(0, k);
String ss = "";
int max = 0;
for (int i = 0; i < s.length() - k; i++) {
ss = s.substring(i, i + k);
int count = 0;
for (int j = 0; j < ss.length(); j++) {
if (ss.charAt(j) == 'H') {
count++;
}
}
if (count > max) {
max = count;
}
}
System.out.println(k - max);
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.io.PrintWriter;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
// 1 = H, 0 = T
int n = in.nextInt();
String line = in.next();
int h = 0;
for (int i = 0; i < line.length(); i++) {
if(line.charAt(i)=='H') h++;
}
line = line + line;
int min = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
int ans = 0;
for (int j = i; j < i+h; j++) {
if(line.charAt(j)!='H') ans++;
}
if(min>ans) min = ans;
}
out.print(min);
in.close();
out.close();
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.io.*;
import java.util.*;
public class HamstersAndTigers
{
Scanner in;
PrintWriter out;
HamstersAndTigers()
{
in = new Scanner(System.in);
out = new PrintWriter(System.out);
}
HamstersAndTigers(String i, String o) throws FileNotFoundException
{
in = new Scanner(new File(i));
out = new PrintWriter(new File(o));
}
public void finalize()
{
out.flush();
in.close();
out.close();
}
void solve()
{
int i = 0,
h = 0,
n = in.nextInt();
String buf = "";
char[] ht = in.next().toCharArray();
for(i = 0; i < n; ++i)
if(ht[i] == 'H')
++h;
for(i = 0; i < h; ++i)
buf += 'H';
for(i = 0; i < n - h; ++i)
buf += 'T';
int diff = (1 << 28);
for(i = 0; i < n; ++i)
{
int tmp = 0;
for(int j = 0; j < n; ++j)
if(buf.charAt(j) != ht[(i + j) % n])
++tmp;
diff = Math.min(tmp, diff);
}
out.println(diff / 2);
}
public static void main(String[] args) throws FileNotFoundException
{
HamstersAndTigers t = new HamstersAndTigers();
t.solve();
t.finalize();
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
int size= Integer.parseInt(r.readLine());
String line = r.readLine();
int counter =0;
for (int i = 0; i < line.length(); i++) {
if(line.charAt(i)=='H')counter++;
}
int minimum = Integer.MAX_VALUE;
for (int i = 0; i < line.length(); i++) {
if(line.charAt(i)=='H'){
int current = 0;
for (int j = i; j < i+counter; j++) {
if(line.charAt(j%line.length())=='T')current++;
}
minimum = Math.min(current, minimum);
}
}
System.out.println(minimum);
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.util.*;
import java.io.*;
import static java.lang.Math.*;
import java.math.*;
public class Main implements Runnable {
BufferedReader in;
PrintStream out;
StringTokenizer st = new StringTokenizer("");
static boolean local = false;
public static void main(String [] args) throws Exception {
if (args.length > 0) local = true;
new Thread(new Main()).start();
}
void printExit(String s) {
out.println(s);
System.exit(0);
}
public void run() {
try {
Locale.setDefault(Locale.US);
in = local ? new BufferedReader(new FileReader("input.txt")) : new BufferedReader(new InputStreamReader(System.in));
out = local ? new PrintStream(new File("output.txt")) : new PrintStream(System.out);
int n = nextInt();
char [] c = in.readLine().toCharArray();
int t = 0;
for (int i = 0; i < n; i++)
if (c[i] == 'T') t++;
int ans = n;
for (int i = 0; i < n; i++) {
int cnt = 0;
for (int j = 0; j < t; j++)
if (c[(i + j) % n] == 'H')
cnt++;
ans = min(ans, cnt);
}
out.println(ans);
}
catch (Exception e) {
e.printStackTrace();
}
}
boolean seekForToken() {
try {
while (!st.hasMoreTokens()) {
String s = in.readLine();
if (s == null) {
return false;
}
st = new StringTokenizer(s);
}
return true;
}
catch (IOException e) {
e.printStackTrace();
return false;
}
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
BigInteger nextBigInteger() {
return new BigInteger(nextToken());
}
String nextToken() {
seekForToken();
return st.nextToken();
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.util.*;
import java.io.*;
import static java.util.Arrays.*;
import static java.lang.Math.*;
import java.math.*;
public class Main {
void run() throws IOException {
int n = in.nextInt();
char[] c = in.next().toCharArray();
int[][] t = new int[n][n];
int[][] h = new int[n][n];
int allt = 0, allh = 0;
for (int i = 0; i < n; i++) {
if (c[i] == 'T') {
allt++;
} else {
allh++;
}
}
for (int i = 0; i < n; i++) {
if (c[i] == 'T') {
t[i][i] = 1;
h[i][i] = 0;
} else {
t[i][i] = 0;
h[i][i] = 1;
}
for (int j = i + 1; j < n; j++) {
if (c[j] == 'T') {
t[i][j] = t[i][j - 1] + 1;
h[i][j] = h[i][j - 1];
} else {
h[i][j] = h[i][j - 1] + 1;
t[i][j] = t[i][j - 1];
}
}
}
for (int i = 1; i < n; i++) {
t[i][i - 1] = allt;
h[i][i - 1] = allh;
for (int j = 0; j < i - 1; j++) {
t[i][j] = allt - t[j + 1][i - 1];
h[i][j] = allh - h[j + 1][i - 1];
}
}
int r = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (h[i][j] == t[(j + 1) % n][(i - 1 + n) % n]) {
r = min(r, h[i][j]);
}
if (t[i][j] == h[(j + 1) % n][(i - 1 + n) % n]) {
r = min(r, t[i][j]);
}
}
}
out.println(r);
/* for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
out.print(t[i][j] + " ");
}
out.println();
}
out.println();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
out.print(h[i][j] + " ");
}
out.println();
}*/
}
class pair implements Comparable <pair> {
int x, y;
pair(int x, int y) {
this.x = x;
this.y = y;
}
public int compareTo (pair p) {
if (x != p.x) {
return x - p.x;
} else {
return y - p.y;
}
}
}
static PrintWriter out;
static Scanner in;
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.US);
//final String FILENAME = "jury"; in = new Scanner (new File (FILENAME + ".in")); out = new PrintWriter (new File(FILENAME + ".out"));
in = new Scanner (System.in); out = new PrintWriter (System.out);
new Main().run();
/*out = new PrintWriter (System.out);
final int NUMBER_OF_TESTS = 35;
for (int i = 1; i <= NUMBER_OF_TESTS; i++) {
Scanner test = new Scanner (new File ("tests/" + i + ".in"));
Scanner right = new Scanner (new File ("tests/" + i + ".out"));
String get_right = right.nextLine();
String get_test = new Main().run(test);
if (get_right.equals(get_test)) {
out.println("Test #" + i + ": " + "OK!");
} else {
out.println("Test #" + i + ": " + "ERROR!");
out.println("Expected: " + get_right);
out.println("Received: " + get_test);
break;
}
}*/
out.close();
}
} | linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.util.Scanner;
/**
*
* @author igor_kz
*/
public class C46 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int number = in.nextInt();
String s = in.next();
int cH = 0;
int n = s.length();
for (int i = 0 ; i < n ; i++)
if (s.charAt(i) == 'H') cH++;
String ss = "";
for (int i = 0 ; i < cH ; i++)
ss += "H";
for (int i = 0 ; i < n - cH ; i++)
ss += "T";
int res = Integer.MAX_VALUE;
for (int i = 0 ; i < n ; i++) {
int cur = countDifference(ss , s);
res = Math.min(res , cur);
ss = ss.substring(1) + ss.charAt(0);
}
System.out.println(res);
}
public static int countDifference(String ss, String s) {
int cnt = 0;
for (int i = 0 ; i < ss.length() ; i++)
if (ss.charAt(i) != s.charAt(i)) cnt++;
return cnt / 2;
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
//package round43;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class C {
static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static PrintWriter out = new PrintWriter(System.out);
static String nextToken() throws IOException{
while (st==null || !st.hasMoreTokens()){
String s = bf.readLine();
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
static int nextInt() throws IOException{
return Integer.parseInt(nextToken());
}
static String nextStr() throws IOException{
return nextToken();
}
static int f(byte s[], int n){
int l = 0,
r = n-1;
int res = 0;
do{
while (l<n && s[l]=='H')
l++;
while (r>=0 && s[r]=='T')
r--;
if (l < r){
res++;
}
l++;
r--;
}
while (l < r);
return res;
}
public static void main(String[] args) throws IOException{
int n = nextInt();
byte s[] = nextStr().getBytes();
int res = f(s, n);
for (int i=1; i<n; i++){
byte c = s[0];
for (int j=0; j<n-1; j++)
s[j] = s[j+1];
s[n-1] = c;
res = Math.min(res, f(s, n));
}
out.println(res);
out.flush();
}
}
| linear | 46_C. Hamsters and Tigers | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class pr1073B {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int n = Integer.parseInt(br.readLine());
int[] a = new int[n];
int[] b = new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(st.nextToken());
}
st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
b[i] = Integer.parseInt(st.nextToken());
}
solve(n, a, b, out);
out.flush();
out.close();
}
private static void solve(int n, int[] a, int[] b, PrintWriter out) {
boolean[] book = new boolean[n+1];
boolean f;
int j1 = 0, j2 = 0;
for (int i = 0; i < n; i++) {
f = false;
int num = b[i];
if(!book[num]) {
f = true;
j1 = j2;
for (;j2 < n; j2++) {
book[a[j2]] = true;
if (a[j2] == num) {
j2++;
break;
}
}
}
out.print(f ? j2-j1 + " ": 0 + " ");
}
}
}
| linear | 1073_B. Vasya and Books | CODEFORCES |
import java.util.*;
public class Test { public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n= sc.nextInt();
int x= (int)Math.sqrt(n) ;
int a[] = new int[n+5];
for(int i=1,o=n,j;i<=n;i+=x)
for(j=(int)Math.min(i+x-1,n);j>=i;a[j--]=o--);
for(int i=1;i<=n;i++)System.out.print(a[i]+" ");
System.out.println();
}
} | linear | 1017_C. The Phone Number | CODEFORCES |
import java.util.Scanner;
public class Solution {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
String s = sc.next();
StringBuilder ans = new StringBuilder();
int count = 0;
int open = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
ans.append("(");
count++;
open++;
} else {
ans.append(")");
open--;
}
if (count == k / 2) {
break;
}
}
while (open > 0) {
ans.append(")");
open--;
}
System.out.println(ans.toString());
}
} | linear | 1023_C. Bracket Subsequence | CODEFORCES |
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int n=scan.nextInt();
int m=scan.nextInt();
int[] game=new int[n];
int[] bill=new int[m];
for (int i = 0; i <n ; i++) {
game[i]=scan.nextInt();
}
for (int i = 0; i <m ; i++) {
bill[i]=scan.nextInt();
}
int i=0;
int j=0;
int ans=0;
while (i<m){
boolean f=true;
for (int k = j; k <n ; k++) {
if (bill[i]>=game[k]){
ans++;
i++;
j=k+1;
f=false;
break;
}
}
if (f){
break;
}
}
System.out.println(ans);
}
}
| linear | 1009_A. Game Shopping | CODEFORCES |
import java.util.*;
import java.io.*;
public class A
{
public static void main(String ar[]) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s1[]=br.readLine().split(" ");
String s2[]=br.readLine().split(" ");
int n=Integer.parseInt(s1[0]);
int m=Integer.parseInt(s1[1]);
int a[]=new int[n];
int b[]=new int[n];
int c[]=new int[n];
int d[]=new int[n];
HashSet<Integer> hs=new HashSet<Integer>();
hs.add(0);
hs.add(m);
int max=0;
for(int i=0;i<n;i++)
{
a[i]=Integer.parseInt(s2[i]);
if(i%2==0)
b[i]=1;
hs.add(a[i]);
}
c[0]=a[0];
for(int i=1;i<n;i++)
{
if(b[i]==0)
c[i]=c[i-1];
else
c[i]=c[i-1]+a[i]-a[i-1];
}
if(b[n-1]==0)
d[n-1]=m-a[n-1];
for(int i=n-2;i>=0;i--)
{
if(b[i]==1)
d[i]=d[i+1];
else
d[i]=d[i+1]+a[i+1]-a[i];
}
max=c[n-1];
if(b[n-1]==0)
max+=m-a[n-1];
//System.out.println(max);
for(int i=n-1;i>=0;i--)
{
int u=a[i]-1;
int v=a[i]+1;
if(!hs.contains(u))
{
if(b[i]==0)
{
int r=1+m-a[i]-d[i]+c[i-1];
max=Math.max(max,r);
}
else
{
int l=0;
if(i>0)
l=a[i-1];
int r=c[i]-1+m-a[i]-d[i];
max=Math.max(max,r);
}
}
if(!hs.contains(v))
{
if(b[i]==0)
{
if(i==n-1)
{
int r=c[i]+1;
max=Math.max(max,r);
}
else
{
int r=c[i]+1+m-a[i+1]-d[i+1];
max=Math.max(max,r);
}
}
else
{
if(i==n-1)
{
int r=c[i]+m-a[i]-1;
max=Math.max(max,r);
}
else
{
int r=c[i]+m-a[i+1]-d[i+1]+a[i+1]-1-a[i];
max=Math.max(max,r);
}
}
}
}
System.out.println(max);
}
} | linear | 1000_B. Light It Up | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class LightItUp {
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());
int m = Integer.parseInt(st.nextToken());
int previous = 0;
int array[] = new int[n+1];
int answer = 0;
StringTokenizer st1 = new StringTokenizer(br.readLine());
for(int i = 0; i < n; i++){
array[i] = Integer.parseInt(st1.nextToken());
if(i % 2 == 0){
answer += (array[i] - previous);
}
previous = array[i];
}
if(n % 2 == 0){
answer += (m - previous);
}
previous = m;
int max = Integer.MAX_VALUE;
while(n-- != 0){
int temp = array[n];
if(n%2 == 0){
array[n] = array[n+1] - (previous - array[n]);
}
else{
array[n] = array[n+1] + (previous - array[n]);
}
previous = temp;
max = Math.min(max, array[n]);
}
if(max>=-1){
System.out.println(answer);
}
else{
System.out.println(answer - (max+1));
}
}
}
| linear | 1000_B. Light It Up | CODEFORCES |
import java.util.*;
public class A
{
public static int palin(String str)
{
int flag=0;
int l=str.length();
for(int i=0;i<l/2;i++)
{
if(str.charAt(i)!=str.charAt(l-i-1))
{
flag=1;
break;
}
}
if(flag==1)
return 0;
else
return 1;
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String str=sc.next();
HashSet<Character> hs=new HashSet<>();
for(int i=0;i<str.length();i++)
{
hs.add(str.charAt(i));
}
if(hs.size()==1)
System.out.println(0);
else if(palin(str)==0)
System.out.println(str.length());
else
System.out.println(str.length()-1);
}
} | linear | 981_A. Antipalindrome | CODEFORCES |
import java.util.*;
public class Main {
static int n=5;
static int[] arr=new int[5];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
for (int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
for (int i=0;i<n;i++)
{
if (arr[i]>=0)
{
arr[i]=-arr[i]-1;
}
}
if (n%2!=0)
{
int min=0;
for (int i=1;i<n;i++)
{
if (arr[i]<arr[min])
min=i;
}
arr[min]=-arr[min]-1;
}
for (int x:arr)
{
System.out.print(x + " ");
}
}
} | linear | 1180_B. Nick and Array | CODEFORCES |
import java.util.Scanner;
public class NickAndArray {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int array[]=new int[n];
int max=Integer.MAX_VALUE;
int index=0;
for(int i=0;i<n;i++)
{
int k=sc.nextInt();
array[i]=k;
if(array[i]>=0)
{
array[i]=-array[i]-1;
}
if(array[i]<max)
{
max=array[i];
index=i;
}
}
if(n%2!=0)
{
array[index]=-array[index]-1;
}
for(int i=0;i<n;i++)
{
System.out.print(array[i]+" " );
}
}
}
| linear | 1180_B. Nick and Array | CODEFORCES |
import java.util.*;
import java.io.*;
import java.math.*;
public class round569d2b {
public static void main(String args[]) {
FastScanner in = new FastScanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
if (n % 2 == 0) {
for (int i = 0; i < n; i++) {
if (arr[i] >= 0) {
arr[i] = -1*arr[i]-1;
}
}
}
else {
int max = Integer.MIN_VALUE;
int maxIndex = 0;
for (int i = 0; i < n; i++) {
int elem = arr[i];
if (elem < 0) {
elem = -1*elem-1;
}
if (elem > max) {
max = elem;
maxIndex = i;
}
}
for (int i = 0; i < n; i++) {
if (i == maxIndex) {
if (arr[i] < 0) {
arr[i] = -1*arr[i]-1;
}
}
else {
if (arr[i] >= 0) {
arr[i] = -1*arr[i]-1;
}
}
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n ;i++) {
sb.append(arr[i] + " ");
}
System.out.println(sb);
}
// ======================================================================================
// =============================== Reference Code =======================================
// ======================================================================================
static int greatestDivisor(int n) {
int limit = (int) Math.sqrt(n);
int max = 1;
for (int i = 2; i <= limit; i++) {
if (n % i == 0) {
max = Integer.max(max, i);
max = Integer.max(max, n / i);
}
}
return max;
}
// Method to return all primes smaller than or equal to
// n using Sieve of Eratosthenes
static boolean[] sieveOfEratosthenes(int n) {
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
boolean prime[] = new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
prime[0] = false;
prime[1] = false;
for (int p = 2; p * p <= n; p++) {
// If prime[p] is not changed, then it is a prime
if (prime[p] == true) {
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
return prime;
}
// Binary search for number greater than or equal to target
// returns -1 if number not found
private static int bin_gteq(int[] a, int key) {
int low = 0;
int high = a.length;
int max_limit = high;
while (low < high) {
int mid = low + (high - low) / 2;
if (a[mid] < key) {
low = mid + 1;
} else
high = mid;
}
return high == max_limit ? -1 : high;
}
public static int gcd(int a, int b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
static class Tuple<X, Y> {
public final X x;
public final Y y;
public Tuple(X x, Y y) {
this.x = x;
this.y = y;
}
public String toString() {
return "(" + x + "," + y + ")";
}
}
static class Tuple3<X, Y, Z> {
public final X x;
public final Y y;
public final Z z;
public Tuple3(X x, Y y, Z z) {
this.x = x;
this.y = y;
this.z = z;
}
public String toString() {
return "(" + x + "," + y + "," + z + ")";
}
}
static Tuple3<Integer, Integer, Integer> gcdExtended(int a, int b, int x, int y) {
// Base Case
if (a == 0) {
x = 0;
y = 1;
return new Tuple3(0, 1, b);
}
int x1 = 1, y1 = 1; // To store results of recursive call
Tuple3<Integer, Integer, Integer> tuple = gcdExtended(b % a, a, x1, y1);
int gcd = tuple.z;
x1 = tuple.x;
y1 = tuple.y;
// Update x and y using results of recursive
// call
x = y1 - (b / a) * x1;
y = x1;
return new Tuple3(x, y, gcd);
}
// Returns modulo inverse of a
// with respect to m using extended
// Euclid Algorithm. Refer below post for details:
// https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/
static int inv(int a, int m) {
int m0 = m, t, q;
int x0 = 0, x1 = 1;
if (m == 1)
return 0;
// Apply extended Euclid Algorithm
while (a > 1) {
// q is quotient
q = a / m;
t = m;
// m is remainder now, process
// same as euclid's algo
m = a % m;
a = t;
t = x0;
x0 = x1 - q * x0;
x1 = t;
}
// Make x1 positive
if (x1 < 0)
x1 += m0;
return x1;
}
// k is size of num[] and rem[].
// Returns the smallest number
// x such that:
// x % num[0] = rem[0],
// x % num[1] = rem[1],
// ..................
// x % num[k-2] = rem[k-1]
// Assumption: Numbers in num[] are pairwise
// coprime (gcd for every pair is 1)
static int findMinX(int num[], int rem[], int k) {
// Compute product of all numbers
int prod = 1;
for (int i = 0; i < k; i++)
prod *= num[i];
// Initialize result
int result = 0;
// Apply above formula
for (int i = 0; i < k; i++) {
int pp = prod / num[i];
result += rem[i] * inv(pp, num[i]) * pp;
}
return result % prod;
}
/**
* Source: Matt Fontaine
*/
static class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int chars;
public FastScanner(InputStream stream) {
this.stream = stream;
}
int read() {
if (chars == -1)
throw new InputMismatchException();
if (curChar >= chars) {
curChar = 0;
try {
chars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (chars <= 0)
return -1;
}
return buf[curChar++];
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndline(c));
return res.toString();
}
}
} | linear | 1180_B. Nick and Array | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in Actual solution is at the top
*
* @author MaxHeap
*/
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);
CBanhMi solver = new CBanhMi();
solver.solve(1, in, out);
out.close();
}
static class CBanhMi {
long mod = (long) (1e9 + 7);
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int q = in.nextInt();
long[] two = new long[n + 1];
two[0] = 1;
for (int i = 1; i <= n; ++i) {
two[i] = (two[i - 1] * 2L);
two[i] %= mod;
}
char[] s = in.nextCharArray();
int[] acc = new int[n + 1];
for (int i = 1; i <= n; ++i) {
acc[i] = s[i - 1] == '0' ? 0 : 1;
acc[i] += acc[i - 1];
}
// 0 0 1 1 | 1: 1 1 2| 2: 2 3| 4: 5| 9
// 0 1 1 1| 1: 1 2 2| 2: 3 3| 5: 6| 11
// 0 1 1 wwqwq| 1: 1 2 2| 3: 5 3| 8: 8| 16
// 0 0 1 1| 1: 1 1 2| 3: 3 3| 6: 6| 12
// 0 0 0 1| 1: 1 1 1| 2: 2 2| 4: 4| 8
while (q-- > 0) {
int f = in.nextInt();
int t = in.nextInt();
int ones = acc[t] - acc[f - 1];
int zeros = (t - f + 1) - ones;
if (ones == 0) {
out.println(0);
} else {
long ans = two[t - f + 1] - (zeros > 0 ? two[zeros] : 0);
if (zeros == 0) {
--ans;
}
ans = (ans + mod) % mod;
out.println(ans);
}
}
}
}
static class InputReader implements FastIO {
private InputStream stream;
private static final int DEFAULT_BUFFER_SIZE = 1 << 16;
private static final int EOF = -1;
private byte[] buf = new byte[DEFAULT_BUFFER_SIZE];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (this.numChars == EOF) {
throw new UnknownError();
} else {
if (this.curChar >= this.numChars) {
this.curChar = 0;
try {
this.numChars = this.stream.read(this.buf);
} catch (IOException ex) {
throw new InputMismatchException();
}
if (this.numChars <= 0) {
return EOF;
}
}
return this.buf[this.curChar++];
}
}
public int nextInt() {
int c;
for (c = this.read(); isSpaceChar(c); c = this.read()) {
}
byte sgn = 1;
if (c == 45) {
sgn = -1;
c = this.read();
}
int res = 0;
while (c >= 48 && c <= 57) {
res *= 10;
res += c - 48;
c = this.read();
if (isSpaceChar(c)) {
return res * sgn;
}
}
throw new InputMismatchException();
}
public String next() {
int c;
while (isSpaceChar(c = this.read())) {
}
StringBuilder result = new StringBuilder();
result.appendCodePoint(c);
while (!isSpaceChar(c = this.read())) {
result.appendCodePoint(c);
}
return result.toString();
}
public static boolean isSpaceChar(int c) {
return c == 32 || c == 10 || c == 13 || c == 9 || c == EOF;
}
public char[] nextCharArray() {
return next().toCharArray();
}
}
static interface FastIO {
}
}
| linear | 1062_C. Banh-mi | CODEFORCES |
import java.util.*;
public class B {
public B () {
int N = sc.nextInt();
int a = sc.nextInt();
int b = sc.nextInt();
int [] P = sc.nextInts();
TreeSet<Integer> S = new TreeSet<>();
Set<Integer> A = new HashSet<>();
Set<Integer> B = new HashSet<>();
for (int p : P) S.add(p);
while (!S.isEmpty()) {
int q = S.first();
int x = a - q, y = b - q;
if (S.contains(x) && S.contains(y)) {
if (x > y) {
S.remove(q); S.remove(x);
A.add(q); A.add(x);
} else {
S.remove(q); S.remove(y);
B.add(q); B.add(y);
}
}
else if (S.contains(x)) {
S.remove(q); S.remove(x);
A.add(q); A.add(x);
}
else if (S.contains(y)) {
S.remove(q); S.remove(y);
B.add(q); B.add(y);
}
else
exit("NO");
}
int [] res = new int[N];
for (int i : rep(N))
if (B.contains(P[i]))
res[i] = 1;
print("YES");
exit(res);
}
private static int [] rep(int N) { return rep(0, N); }
private static int [] rep(int S, int T) { if (T <= S) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; }
////////////////////////////////////////////////////////////////////////////////////
private final static IOUtils.MyScanner sc = new IOUtils.MyScanner();
private static void print (Object o, Object ... A) { IOUtils.print(o, A); }
private static void exit (Object o, Object ... A) { IOUtils.print(o, A); IOUtils.exit(); }
private static class IOUtils {
public static class MyScanner {
public String next() { newLine(); return line[index++]; }
public int nextInt() { return Integer.parseInt(next()); }
public String nextLine() { line = null; return readLine(); }
public String [] nextStrings() { return split(nextLine()); }
public int [] nextInts() {
String [] L = nextStrings();
int [] res = new int [L.length];
for (int i = 0; i < L.length; ++i)
res[i] = Integer.parseInt(L[i]);
return res;
}
//////////////////////////////////////////////
private boolean eol() { return index == line.length; }
private String readLine() {
try {
return r.readLine();
} catch (Exception e) {
throw new Error (e);
}
}
private final java.io.BufferedReader r;
private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); }
private MyScanner (java.io.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 = split(readLine());
index = 0;
}
}
private String [] split(String s) { return s.length() > 0 ? s.split(" ") : new String [0]; }
}
private static String build(Object o, Object ... A) { return buildDelim(" ", o, A); }
private static String buildDelim(String delim, Object o, Object ... A) {
StringBuilder b = new StringBuilder();
append(b, o, delim);
for (Object p : A)
append(b, p, delim);
return b.substring(delim.length());
}
//////////////////////////////////////////////////////////////////////////////////
private static void start() { if (t == 0) t = millis(); }
private static void append(StringBuilder b, Object o, String delim) {
if (o.getClass().isArray()) {
int len = java.lang.reflect.Array.getLength(o);
for (int i = 0; i < len; ++i)
append(b, java.lang.reflect.Array.get(o, i), delim);
} else if (o instanceof Iterable<?>)
for (Object p : (Iterable<?>) o)
append(b, p, delim);
else {
if (o instanceof Double)
o = new java.text.DecimalFormat("#.############").format(o);
b.append(delim).append(o);
}
}
private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out);
private static void print(Object o, Object ... A) { pw.println(build(o, A)); }
private static void err(Object o, Object ... A) { System.err.println(build(o, A)); }
private static void exit() {
IOUtils.pw.close();
System.out.flush();
err("------------------");
err(IOUtils.time());
System.exit(0);
}
private static long t;
private static long millis() { return System.currentTimeMillis(); }
private static String time() { return "Time: " + (millis() - t) / 1000.0; }
}
public static void main (String[] args) { new B(); IOUtils.exit(); }
}
| linear | 468_B. Two Sets | CODEFORCES |
/*
* Hopefully this is AC :D
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.StringTokenizer;
import java.util.Arrays;
public class TwoSets {
static ArrayList<Integer> g[];
static boolean visited[];
static int ans[],p[],orig[];
static int n,a,b;
@SuppressWarnings("unchecked")
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter w = new PrintWriter(System.out);
StringTokenizer st1 = new StringTokenizer(br.readLine());
n = ip(st1.nextToken());
a = ip(st1.nextToken());
b = ip(st1.nextToken());
g = new ArrayList[n];
visited = new boolean[n];
ans = new int[n];
p = new int[n];
orig = new int[n];
StringTokenizer st2 = new StringTokenizer(br.readLine());
for(int i=0;i<n;i++){
p[i] = ip(st2.nextToken());
orig[i] = p[i];
g[i] = new ArrayList<Integer>();
}
Arrays.sort(p);
boolean impossible = false;
for(int i=0;i<n;i++){
int i1 = Arrays.binarySearch(p, a-p[i]);
int i2 = Arrays.binarySearch(p, b-p[i]);
if(i1 < 0 || i1 >= n) i1 = -1;
if(i2 < 0 || i2 >= n) i2 = -1;
if(i1 == -1 && i2 != -1) //if only (b-x) present then both must belong to set 1
g[i].add(i2);
else if(i1 != -1 && i2 == -1) //if only (a-x) present then both must belong to set 0
g[i].add(i1);
else if(i1 != -1 && i2 != -1){ //both present hence all 3 should be in same set,doesn't matter which
g[i].add(i1);
g[i].add(i2);
}
else{ //if none present then not possible to be in any set
impossible = true;
break;
}
}
if(impossible){//if any element without both a-x and b-x found
System.out.println("NO");
return;
}
//Edge between a and b means they must be present in same set
//ans[i] =0 or ans[i] =1 means it must be compulsory be present in that set
//ans[i] = -1 means no restrictions on it's set number
LinkedList<Integer> q = new LinkedList();//Queue
for(int i=0;i<n;i++){
if(visited[i] == false){
ArrayList<Integer> curq = new ArrayList<Integer>(); //contains indices of all nodes in this connected component
curq.add(i);
q.add(i);
visited[i] = true;
while(!q.isEmpty()){
int curr = q.remove();
int s = g[curr].size();
for(int j=0;j<s;j++){
if(!visited[g[curr].get(j)]){
visited[g[curr].get(j)] = true;
curq.add(g[curr].get(j));
q.add(g[curr].get(j));
}
}
}
boolean found = true;
int s = curq.size();
int temp[] = new int[s];
for(int j=0;j<s;j++)
temp[j] = p[curq.get(j)];
Arrays.sort(temp);
int anss = -1;
for(int j=0;j<s;j++){
int i3 = Arrays.binarySearch(temp, a - temp[j]);
if(i3 < 0 || i3 >= n){
found = false;
break;
}
}
if(!found){
found = true;
for(int j=0;j<s;j++){
int i3 = Arrays.binarySearch(temp, b - temp[j]);
if(i3 < 0 || i3 >= n){
found = false;
break;
}
}
if(found)
anss = 1;
else{
impossible = true;
break;
}
}
else
anss = 0;
for(int j=0;j<s;j++)
ans[curq.get(j)] = anss;
}
}
if(!impossible){
w.println("YES");
for(int i=0;i<n;i++){
int i1 = Arrays.binarySearch(p, orig[i]);
if(ans[i1] == -1) ans[i1] = 1;
w.print(ans[i1] + " ");
}
w.println();
}
else
w.println("NO");
w.close();
}
public static int ip(String s){
return Integer.parseInt(s);
}
}
| linear | 468_B. Two Sets | CODEFORCES |
import java.util.InputMismatchException;
import java.math.BigInteger;
import java.io.*;
import java.util.*;
/**
* Generated by Contest helper plug-in
* Actual solution is at the bottom
*/
public class Main {
public static void main(String[] args) {
InputReader in = new StreamInputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
run(in, out);
}
public static void run(InputReader in, PrintWriter out) {
Solver solver = new Task();
solver.solve(1, in, out);
Exit.exit(in, out);
}
}
abstract class InputReader {
private boolean finished = false;
public abstract int read();
public long readLong() {
return new BigInteger(readString()).longValue();
}
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();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public void setFinished(boolean finished) {
this.finished = finished;
}
public abstract void close();
}
class StreamInputReader extends InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public StreamInputReader(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 void close() {
try {
stream.close();
} catch (IOException ignored) {
}
}
}
class Exit {
private Exit() {
}
public static void exit(InputReader in, PrintWriter out) {
in.setFinished(true);
in.close();
out.close();
}
}
interface Solver {
public void solve(int testNumber, InputReader in, PrintWriter out);
}
class Task implements Solver {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.readInt();
int a = in.readInt();
int b = in.readInt();
if (a==b) {
b = 0;
}
boolean[] where = new boolean[n];
HashSet<Integer> set = new HashSet<Integer>();
HashMap<Integer,Integer> indexmap = new HashMap<Integer,Integer>();
for (int i = 0; i<n; i++) {
int x = in.readInt();
indexmap.put(x, i);
set.add(x);
}
while (set.size() > 0) {
int size = set.size();
HashSet<Integer> todo = new HashSet<Integer>();
HashSet<Integer> used = new HashSet<Integer>();
for (int x : set) {
if (used.contains(x))
continue;
int ax = a-x;
int bx = b-x;
if ((set.contains(ax) && !used.contains(ax)) && (set.contains(bx) && !used.contains(bx))) {
todo.add(x);
} else if (set.contains(ax) && !used.contains(ax)) {
used.add(x);
used.add(ax);
todo.remove(ax);
//chain
bx = b-ax;
while (set.contains(bx) && !used.contains(bx)) {
x = bx;
ax = a-x;
if (!set.contains(ax) || used.contains(ax)) {
System.out.println("NO");
return;
}
todo.remove(x);
todo.remove(ax);
used.add(x);
used.add(ax);
bx = b-ax;
}
} else if (set.contains(bx) && !used.contains(bx)) {
used.add(x);
used.add(bx);
todo.remove(bx);
where[indexmap.get(bx)] = true;
where[indexmap.get(x)] = true;
//chain
ax = a-bx;
while (set.contains(ax) && !used.contains(ax)) {
x = ax;
bx = b-x;
if (!set.contains(bx) || used.contains(bx)) {
System.out.println("NO");
return;
}
todo.remove(x);
todo.remove(bx);
used.add(x);
used.add(bx);
where[indexmap.get(bx)] = true;
where[indexmap.get(x)] = true;
ax = a-bx;
}
} else {
System.out.println("NO");
return;
}
}
set = todo;
if (set.size() == size) {
System.out.println("Set size constant!!");
break;
}
}
System.out.println("YES");
for (int i = 0; i<n; i++)
if (where[i])
System.out.print("1 ");
else
System.out.print("0 ");
}
}
class num {
}
///
| linear | 468_B. Two Sets | CODEFORCES |
import java.io.IOException;
import java.util.Arrays;
import java.io.FilterInputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.TreeSet;
import java.io.BufferedInputStream;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Zyflair Griffane
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputUtil in = new InputUtil(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
HashMap<Integer, Integer> left = new HashMap<Integer, Integer>();
public void solve(int testNumber, InputUtil in, PrintWriter out) {
int n = in.nextInt();
int a = in.nextInt();
int b = in.nextInt();
int[] res = new int[n];
int[] arr = in.nextIntArray(n);
IntDeque[] adj = IntDeque.IntDeques(n);
boolean[] self = new boolean[n];
boolean[] assigned = new boolean[n];
for (int i = 0; i < n; i++) {
left.put(arr[i], i);
}
for (int i = 0; i < n; i++) {
int x = arr[i];
boolean canA = left.containsKey(a - x);
boolean canB = left.containsKey(b - x);
if (!canA && !canB) {
out.println("NO");
return;
}
if (left.containsKey(a - x)) {
self[i] |= x == a - x;
if (x != a - x) {
adj[i].add(left.get(a - x));
}
}
if (left.containsKey(b - x)) {
self[i] |= x == b - x;
if (x != b - x) {
adj[i].add(left.get(b - x));
}
}
}
if (a == b) {
out.println("YES");
out.println(IntArrayUtil.toString(res));
return;
}
for (int iter = 0; iter < 2; iter++) {
for (int i = 0; i < n; i++) {
if (!self[i] && !assigned[i] && (iter == 1 || adj[i].size() == 1)) {
int u = i;
DFS:
while (true) {
assigned[u] = true;
if (self[u] && arr[u] == b - arr[u]) {
res[u] = 1;
break;
}
for (int v : adj[u]) {
if (!assigned[v]) {
assigned[v] = true;
if (arr[u] == b - arr[v]) {
res[u] = res[v] = 1;
}
for (int newU : adj[v]) {
if (!assigned[newU]) {
u = newU;
continue DFS;
}
}
break DFS;
}
}
out.println("NO");
return;
}
}
else if (iter == 1 && !assigned[i] && adj[i].size() == 0 && arr[i] == b - arr[i]) {
res[i] = 1;
}
}
}
out.println("YES");
out.println(IntArrayUtil.toString(res));
}
}
class InputUtil {
JoltyScanner in;
public InputUtil(InputStream istream) {
in = new JoltyScanner(istream);
}
public String next() {
return in.next();
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] nextIntArray (int size) {
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = in.nextInt();
}
return arr;
}
}
class IntDeque implements Iterable<Integer> {
private int capacity;
private int size = 0;
private int front = 0;
private int back = 0;
private int[] deque;
public IntDeque() {
this(16);
}
public IntDeque(int capacity) {
this.capacity = capacity;
deque = new int[capacity];
}
public static IntDeque[] IntDeques(int length) {
IntDeque[] arr = new IntDeque[length];
for (int i = 0; i < length; i++) {
arr[i] = new IntDeque();
}
return arr;
}
public <T extends Iterable<Integer>>IntDeque(T intList) {
this(16);
addAll(intList);
}
public IntDeque(int[] intArr) {
this(16);
for (int i: intArr) {
addLast(i);
}
}
public void add(int x) {
addLast(x);
}
public <T extends Iterable<Integer>>void addAll(T intList) {
for (int i: intList) {
addLast(i);
}
}
public void addLast(int x) {
ensureCapacity();
size++;
deque[back++] = x;
if (back == capacity) {
back = 0;
}
}
public void ensureCapacity() {
if (size < capacity) {
return;
}
int[] newDeque = new int[capacity << 1];
for (int i = 0, j = front; i < size; i++, j++) {
if (j == capacity) {
j = 0;
}
newDeque[i] = deque[j];
}
deque = newDeque;
capacity <<= 1;
front = 0;
back = size;
}
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
int done = 0;
int curr = front;
public boolean hasNext() {
return done < size;
}
public Integer next() {
Integer res = deque[curr++];
if (curr == capacity) {
curr = 0;
}
done++;
return res;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public int size() {
return size;
}
public String toString() {
if (size == 0) {
return "";
}
StringBuilder res = new StringBuilder();
for (int i: this) {
res.append(i);
res.append(" ");
}
res.setLength(res.length() - 1);
return res.toString();
}
}
class IntArrayUtil {
public static String toString(int[] arr) {
return toString(arr, " ");
}
public static String toString(int[] arr, String delimiter) {
StringBuilder res = new StringBuilder();
for (int i: arr) {
res.append(i);
res.append(delimiter);
}
res.setLength(res.length() - delimiter.length());
return res.toString();
}
}
class JoltyScanner {
public static final int BUFFER_SIZE = 1 << 16;
public static final char NULL_CHAR = (char) -1;
StringBuilder str = new StringBuilder();
byte[] buffer = new byte[BUFFER_SIZE];
boolean EOF_FLAG = false;
int bufferIdx = 0, size = 0;
char c = NULL_CHAR;
BufferedInputStream in;
public JoltyScanner(InputStream in) {
this.in = new BufferedInputStream(in, BUFFER_SIZE);
}
public int nextInt() {
long x = nextLong();
if (x > Integer.MAX_VALUE || x < Integer.MIN_VALUE) {
throw new ArithmeticException("Scanned value overflows integer");
}
return (int) x;
}
public long nextLong() {
boolean negative = false;
if (c == NULL_CHAR) {
c = nextChar();
}
for (; !EOF_FLAG && (c < '0' || c > '9'); c = nextChar()) {
if (c == '-') {
negative = true;
}
}
checkEOF();
long res = 0;
for (; c >= '0' && c <= '9'; c = nextChar()) {
res = (res << 3) + (res << 1) + c - '0';
}
return negative ? -res : res;
}
public String next() {
checkEOF();
if (c == NULL_CHAR) {
c = nextChar();
}
while (Character.isWhitespace(c)) {
c = nextChar();
checkEOF();
}
str.setLength(0);
for (; !EOF_FLAG && !Character.isWhitespace(c); c = nextChar()) {
str.append(c);
}
return str.toString();
}
public char nextChar() {
if (EOF_FLAG) {
return NULL_CHAR;
}
while (bufferIdx == size) {
try {
size = in.read(buffer);
if (size == -1) {
throw new Exception();
}
} catch (Exception e) {
EOF_FLAG = true;
return NULL_CHAR;
}
if (size == -1) {
size = BUFFER_SIZE;
}
bufferIdx = 0;
}
return (char) buffer[bufferIdx++];
}
public void checkEOF() {
if (EOF_FLAG) {
throw new EndOfFileException();
}
}
public class EndOfFileException extends RuntimeException {
}
}
| linear | 468_B. Two Sets | CODEFORCES |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* 4 4
* 1 5 3 4
* 1 2
* 1 3
* 2 3
* 3 3
*
*
* @author pttrung
*/
public class A {
public static long Mod = (long) (1e9 + 7);
public static long[][] dp;
public static void main(String[] args) throws FileNotFoundException {
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int n = in.nextInt();
int a = in.nextInt();
int b = in.nextInt();
int[] data = new int[n];
int[]u = new int[n];
int[]s = new int[n];
HashMap<Integer, Integer> map = new HashMap();
for(int i = 0; i < n; i++){
u[i] = i;
data[i] = in.nextInt();
map.put(data[i], i);
}
boolean ok = true;
boolean[]check = new boolean[n];
for(int i = 0; i < n; i++){
if(map.containsKey(a - data[i])){
u[find(i, u)]= u[find(map.get(a- data[i]), u)];
s[i] |= 1;
}
if(map.containsKey(b - data[i])){
u[find(i, u)]= u[find(map.get(b- data[i]), u)];
s[i] |= 2;
}
}
int[]g = new int[n];
Arrays.fill(g,3);
for(int i = 0; i< n; i++){
if(s[i] == 0){
ok = false;
break;
}
g[find(i, u)] &= s[i];
if(g[find(i,u)] == 0){
ok = false;
break;
}
}
//System.out.println(Arrays.toString(g));
if(ok){
out.println("YES");
for(int i = 0; i < n; i++){
if((g[find(i,u)] & 1) == 0){
out.print(1 + " ");
}else{
out.print(0 + " ");
}
}
}else{
out.println("NO");
}
out.close();
}
static int find(int index, int[]u){
if(index != u[index]){
return u[index] = find(u[index], u);
}
return index;
}
public static long pow(int a, int b, long mod) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long v = pow(a, b / 2, mod);
if (b % 2 == 0) {
return (v * v) % mod;
} else {
return (((v * v) % mod) * a) % mod;
}
}
public static int[][] powSquareMatrix(int[][] A, long p) {
int[][] unit = new int[A.length][A.length];
for (int i = 0; i < unit.length; i++) {
unit[i][i] = 1;
}
if (p == 0) {
return unit;
}
int[][] val = powSquareMatrix(A, p / 2);
if (p % 2 == 0) {
return mulMatrix(val, val);
} else {
return mulMatrix(A, mulMatrix(val, val));
}
}
public static int[][] mulMatrix(int[][] A, int[][] B) {
int[][] result = new int[A.length][B[0].length];
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++) {
long temp = 0;
for (int k = 0; k < A[0].length; k++) {
temp += ((long) A[i][k] * B[k][j] % Mod);
temp %= Mod;
}
temp %= Mod;
result[i][j] = (int) temp;
}
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
static class FT {
int[] data;
FT(int n) {
data = new int[n];
}
void update(int index, int val) {
// System.out.println("UPDATE INDEX " + index);
while (index < data.length) {
data[index] += val;
index += index & (-index);
// System.out.println("NEXT " +index);
}
}
int get(int index) {
// System.out.println("GET INDEX " + index);
int result = 0;
while (index > 0) {
result += data[index];
index -= index & (-index);
// System.out.println("BACK " + index);
}
return result;
}
}
static long gcd(long a, long b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
static long pow(long a, int b) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2);
if (b % 2 == 0) {
return val * val % Mod;
} else {
return (val * val % Mod) * a % Mod;
}
}
// static Point intersect(Point a, Point b, Point c) {
// double D = cross(a, b);
// if (D != 0) {
// return new Point(cross(c, b) / D, cross(a, c) / D);
// }
// return null;
// }
//
// static Point convert(Point a, double angle) {
// double x = a.x * cos(angle) - a.y * sin(angle);
// double y = a.x * sin(angle) + a.y * cos(angle);
// return new Point(x, y);
// }
static Point minus(Point a, Point b) {
return new Point(a.x - b.x, a.y - b.y);
}
//
// static Point add(Point a, Point b) {
// return new Point(a.x + b.x, a.y + b.y);
// }
//
/**
* Cross product ab*ac
*
* @param a
* @param b
* @param c
* @return
*/
static double cross(Point a, Point b, Point c) {
Point ab = new Point(b.x - a.x, b.y - a.y);
Point ac = new Point(c.x - a.x, c.y - a.y);
return cross(ab, ac);
}
static double cross(Point a, Point b) {
return a.x * b.y - a.y * b.x;
}
/**
* Dot product ab*ac;
*
* @param a
* @param b
* @param c
* @return
*/
static long dot(Point a, Point b, Point c) {
Point ab = new Point(b.x - a.x, b.y - a.y);
Point ac = new Point(c.x - a.x, c.y - a.y);
return dot(ab, ac);
}
static long dot(Point a, Point b) {
long total = a.x * b.x;
total += a.y * b.y;
return total;
}
static double dist(Point a, Point b) {
long total = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);
return Math.sqrt(total);
}
static long norm(Point a) {
long result = a.x * a.x;
result += a.y * a.y;
return result;
}
static double dist(Point a, Point b, Point x, boolean isSegment) {
double dist = cross(a, b, x) / dist(a, b);
// System.out.println("DIST " + dist);
if (isSegment) {
Point ab = new Point(b.x - a.x, b.y - a.y);
long dot1 = dot(a, b, x);
long norm = norm(ab);
double u = (double) dot1 / norm;
if (u < 0) {
return dist(a, x);
}
if (u > 1) {
return dist(b, x);
}
}
return Math.abs(dist);
}
static long squareDist(Point a, Point b) {
long x = a.x - b.x;
long y = a.y - b.y;
return x * x + y * y;
}
static class Point {
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "Point{" + "x=" + x + ", y=" + y + '}';
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
//System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
//br = new BufferedReader(new FileReader(new File("A-large (2).in")));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
| linear | 468_B. Two Sets | CODEFORCES |
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
public class Main {
static int n;
static int a;
static int b;
static int g;
static int ref;
static int refg;
static HashSet<Integer> cgroup;
static HashMap<Integer,Integer> indexmap;
static HashSet<Integer> nums;
static HashSet<Integer> used;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
n = scan.nextInt();
a = scan.nextInt();
b = scan.nextInt();
boolean[] where = new boolean[n];
indexmap = new HashMap<Integer,Integer>();
used = new HashSet<Integer>();
nums = new HashSet<Integer>();
if (a==b)
b = 0;
for (int i = 0; i<n; i++) {
int x = scan.nextInt();
nums.add(x);
indexmap.put(x,i);
}
scan.close();
for (int x : nums) {
if (used.contains(x))
continue;
cgroup = new HashSet<Integer>();
cgroup.add(x);
g = -1;
refg = -1;
ref = -1;
used.add(x);
if (!spawn(x,a,b) || !spawn(x,b,a)) {
System.out.println("NO");
return;
}
if (cgroup.size()%2==1 && ref == -1) {
System.out.println("NO");
return;
} else {
boolean w = true;
if (g == a)
w = false;
for (int k : cgroup) {
where[indexmap.get(k)] = w;
}
}
}
System.out.println("YES");
for (int i = 0; i<where.length; i++)
if (where[i])
System.out.print("1 ");
else
System.out.print("0 ");
}
private static boolean spawn(int x, int ab, int abo) {
int xab = ab-x;
if (xab == x) {
ref = x;
refg = ab;
} else {
if (nums.contains(xab)) {
cgroup.add(xab);
used.add(xab);
spawn(xab,abo,ab);
} else {
if (g == -1)
g = abo;
else if (g != abo) {
return false;
}
}
}
return true;
}
} | linear | 468_B. Two Sets | CODEFORCES |
import java.io.*;
import java.util.*;
public class B {
void solve() throws IOException {
in = new InputReader("__std");
out = new OutputWriter("__std");
int n = in.readInt();
int a = in.readInt();
int b = in.readInt();
int ma = 0;
int mb = 1;
if (a < b) {
int t = a; a = b; b = t;
t = ma; ma = mb; mb = t;
}
final int[] p = new int[n];
Integer id[] = new Integer[n];
Map<Integer, Integer> pos = new HashMap<Integer, Integer>();
for (int i = 0; i < n; ++i) {
p[i] = in.readInt();
id[i] = i;
pos.put(p[i], i);
}
Arrays.sort(id, new Comparator<Integer>() {
public int compare(Integer i, Integer j) {
return p[i] - p[j];
}
});
int[] mask = new int[n];
Arrays.fill(mask, -1);
boolean flag = true;
for (int i = 0; i < n && flag; ++i) {
if (mask[id[i]] == -1) {
if (p[id[i]] < a) {
if (pos.containsKey(a - p[id[i]])) {
int j = pos.get(a - p[id[i]]);
if (mask[j] != mb) {
mask[id[i]] = mask[j] = ma;
continue;
}
}
if (p[id[i]] < b && pos.containsKey(b - p[id[i]])) {
int j = pos.get(b - p[id[i]]);
if (mask[j] != ma) {
mask[id[i]] = mask[j] = mb;
continue;
}
}
}
flag = false;
}
}
if (flag) {
out.println("YES");
for (int m : mask) {
out.print(m + " ");
}
} else {
out.println("NO");
}
exit();
}
void exit() {
//System.err.println((System.currentTimeMillis() - startTime) + " ms");
out.close();
System.exit(0);
}
InputReader in;
OutputWriter out;
//long startTime = System.currentTimeMillis();
public static void main(String[] args) throws IOException {
new B().solve();
}
class InputReader {
private InputStream stream;
private byte[] buffer = new byte[1024];
private int pos, len;
private int cur;
private StringBuilder sb = new StringBuilder(32);
InputReader(String name) throws IOException {
if (name.equals("__std")) {
stream = System.in;
} else {
stream = new FileInputStream(name);
}
cur = read();
}
private int read() throws IOException {
if (len == -1) {
throw new EOFException();
}
if (pos >= len) {
pos = 0;
len = stream.read(buffer);
if (len == -1) return -1;
}
return buffer[pos++];
}
char readChar() throws IOException {
if (cur == -1) {
throw new EOFException();
}
char res = (char) cur;
cur = read();
return res;
}
int readInt() throws IOException {
if (cur == -1) {
throw new EOFException();
}
while (whitespace()) {
cur = read();
}
if (cur == -1) {
throw new EOFException();
}
int sign = 1;
if (cur == '-') {
sign = -1;
cur = read();
}
int res = 0;
while (!whitespace()) {
if (cur < '0' || cur > '9') {
throw new NumberFormatException();
}
res *= 10;
res += cur - '0';
cur = read();
}
return res * sign;
}
long readLong() throws IOException {
if (cur == -1) {
throw new EOFException();
}
return Long.parseLong(readToken());
}
double readDouble() throws IOException {
if (cur == -1) {
throw new EOFException();
}
return Double.parseDouble(readToken());
}
String readLine() throws IOException {
if (cur == -1) {
throw new EOFException();
}
sb.setLength(0);
while (cur != -1 && cur != '\r' && cur != '\n') {
sb.append((char) cur);
cur = read();
}
if (cur == '\r') {
cur = read();
}
if (cur == '\n') {
cur = read();
}
return sb.toString();
}
String readToken() throws IOException {
if (cur == -1) {
throw new EOFException();
}
while (whitespace()) {
cur = read();
}
if (cur == -1) {
throw new EOFException();
}
sb.setLength(0);
while (!whitespace()) {
sb.append((char) cur);
cur = read();
}
return sb.toString();
}
boolean whitespace() {
return cur == ' ' || cur == '\t' || cur == '\r' || cur == '\n' || cur == -1;
}
boolean eof() {
return cur == -1;
}
}
class OutputWriter {
private PrintWriter writer;
OutputWriter(String name) throws IOException {
if (name.equals("__std")) {
writer = new PrintWriter(System.out);
} else {
writer = new PrintWriter(name);
}
}
void print(String format, Object ... args) {
writer.print(new Formatter(Locale.US).format(format, args));
}
void println(String format, Object ... args) {
writer.println(new Formatter(Locale.US).format(format, args));
}
void print(Object value) {
writer.print(value);
}
void println(Object value) {
writer.println(value);
}
void println() {
writer.println();
}
void close() {
writer.close();
}
}
}
| linear | 468_B. Two Sets | CODEFORCES |
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Map;
/**
* Created by hama_du on 2014/09/21.
*/
public class ProblemB {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
long a = in.nextLong();
long b = in.nextLong();
long[] x = new long[n];
for (int i = 0; i < n; i++) {
x[i] = in.nextLong();
}
Map<Long,Integer> idxmap = new HashMap<>();
for (int i = 0; i < n; i++) {
idxmap.put(x[i], i);
}
if (a == b) {
solve1(x, a, idxmap, out);
return;
}
int[] mark = new int[n];
Arrays.fill(mark, -1);
boolean isok = true;
for (int i = 0 ; i < n ; i++) {
if (mark[i] != -1) {
continue;
}
long w = x[i];
long aw = a - w;
long bw = b - w;
if (idxmap.containsKey(aw) && idxmap.containsKey(bw)) {
continue;
} else if (idxmap.containsKey(bw)) {
long w1 = w;
long w2 = bw;
while (true) {
if (!idxmap.containsKey(w1) || !idxmap.containsKey(w2)) {
break;
}
int i1 = idxmap.get(w1);
int i2 = idxmap.get(w2);
if (mark[i1] == 0 || mark[i2] == 0) {
isok = false;
}
mark[i1] = 1;
mark[i2] = 1;
if (w1 + a - b == w2) {
break;
}
w1 += (a - b);
w2 += (b - a);
}
} else if (idxmap.containsKey(aw)){
long w1 = w;
long w2 = aw;
while (true) {
if (!idxmap.containsKey(w1) || !idxmap.containsKey(w2)) {
break;
}
int i1 = idxmap.get(w1);
int i2 = idxmap.get(w2);
if (mark[i1] == 1 || mark[i2] == 1) {
isok = false;
}
mark[i1] = 0;
mark[i2] = 0;
if (w1 + b - a == w2) {
break;
}
w1 += (b - a);
w2 += (a - b);
}
}
}
for (int i = 0 ; i < n ; i++) {
if (mark[i] == -1) {
isok = false;
break;
}
}
if (isok) {
printAnswer(mark, out);
} else {
out.println("NO");
}
out.flush();
}
private static void printAnswer(int[] mark, PrintWriter out) {
out.println("YES");
StringBuilder ln = new StringBuilder();
for (int m : mark) {
ln.append(' ').append(m);
}
out.println(ln.substring(1));
}
private static void solve1(long[] x, long a, Map<Long, Integer> idxmap, PrintWriter out) {
int[] mark = new int[x.length];
for (int i = 0 ; i < x.length ; i++) {
if (mark[i] == 1) {
continue;
}
long w = x[i];
long wp = a - w;
if (idxmap.containsKey(wp)) {
mark[i] = mark[idxmap.get(wp)] = 1;
}
}
boolean isok = true;
for (int i = 0 ; i < x.length ; i++) {
if (mark[i] == 0) {
isok = false;
break;
}
}
if (isok) {
printAnswer(mark, out);
} else {
out.println("NO");
}
out.flush();
}
public static void debug(Object... o) {
System.err.println(Arrays.deepToString(o));
}
static 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 next() {
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 = next();
while (isSpaceChar(c))
c = next();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = next();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = next();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = next();
while (isSpaceChar(c))
c = next();
long sgn = 1;
if (c == '-') {
sgn = -1;
c = next();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = next();
} 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);
}
}
}
| linear | 468_B. Two Sets | CODEFORCES |
import java.util.Map;
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.TreeMap;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.readInt();
int a = in.readInt();
int b = in.readInt();
TreeMap<Integer, Integer> mp = new TreeMap<Integer, Integer>();
for (int i = 0; i < n; ++i) {
mp.put(in.readInt(), i);
}
int aname = 0;
int bname = 1;
if (a > b) {
int t = a;
a = b;
b = t;
aname = 1;
bname = 0;
}
int[] res = new int[n];
while (mp.size() > 0) {
Map.Entry<Integer, Integer> e = mp.firstEntry();
int val = e.getKey();
if (mp.containsKey(b - val)) {
res[mp.get(val)] = res[mp.get(b - val)] = bname;
mp.remove(val);
mp.remove(b - val);
} else if (mp.containsKey(a - val)) {
res[mp.get(val)] = res[mp.get(a - val)] = aname;
mp.remove(val);
mp.remove(a - val);
} else {
break;
}
}
if (mp.size() > 0) {
out.println("NO");
} else {
out.println("YES");
for (int i = 0; i < n; ++i) {
if (i > 0) out.print(" ");
out.print(res[i]);
}
out.println();
}
}
}
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 static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
| linear | 468_B. Two Sets | CODEFORCES |
import java.util.Map;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Set;
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
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int a = in.nextInt();
int b = in.nextInt();
int[] p = new int[n];
for (int i = 0; i < n; ++i)
p[i] = in.nextInt();
Map<Integer, Integer> position = new HashMap<>(n);
for (int i = 0; i < n; ++i)
position.put(p[i], i);
DisjointSet sets = new DisjointSet(n);
for (int i = 0; i < n; ++i) {
if (position.containsKey(a - p[i]))
sets.joinSet(i, position.get(a - p[i]));
if (position.containsKey(b - p[i]))
sets.joinSet(i, position.get(b - p[i]));
}
Group[] groups = new Group[n];
for (int i = 0; i < n; ++i)
if (sets.getSet(i) == i)
groups[i] = new Group();
for (int i = 0; i < n; ++i)
groups[sets.getSet(i)].value.add(p[i]);
int[] answer = new int[n];
for (Group group : groups) if (group != null) {
if (group.check(a)) {
for (int key : group.value)
answer[position.get(key)] = 0;
} else if (group.check(b)) {
for (int key : group.value)
answer[position.get(key)] = 1;
} else {
out.println("NO");
return;
}
}
out.println("YES");
for (int i = 0; i < n; ++i) {
if (i > 0) out.print(' ');
out.print(answer[i]);
}
out.println();
}
class Group {
Set<Integer> value = new HashSet<>();
boolean check(int sum) {
for (int key : value)
if (!value.contains(sum - key))
return false;
return true;
}
}
}
class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens())
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
class DisjointSet {
private final int[] label;
private int numSets;
private Listener listener;
public DisjointSet(int n, Listener listener) {
label = new int[n];
Arrays.fill(label, -1);
numSets = n;
this.listener = listener;
}
public DisjointSet(int n) {
this(n, null);
}
public int getSet(int at) {
if (label[at] < 0) return at;
return label[at] = getSet(label[at]);
}
public boolean sameSet(int u, int v) {
return getSet(u) == getSet(v);
}
public boolean joinSet(int u, int v) {
if (sameSet(u, v)) return false;
u = getSet(u);
v = getSet(v);
if (label[u] < label[v]) {
int tmp = u;
u = v;
v = tmp;
}
label[v] += label[u];
label[u] = v;
--numSets;
if (listener != null) listener.joined(u, v);
return true;
}
public static interface Listener {
public void joined(int joinedRoot, int root);
}
}
| linear | 468_B. Two Sets | CODEFORCES |
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.Set;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.HashSet;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Mahmoud Aladdin <aladdin3>
*/
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
public void solve(int testNumber, InputReader jin, OutputWriter jout) {
int n = jin.int32();
int a = jin.int32();
int b = jin.int32();
Set<Integer> present = new HashSet<Integer>();
int[] arr = new int[n];
int[] sarr = new int[n];
for(int i = 0; i < n; i++) {
sarr[i] = arr[i] = jin.int32();
present.add(arr[i]);
}
boolean rev = b < a;
if(b < a) {b ^= a; a ^= b; b ^= a; }
Arrays.sort(sarr);
Set<Integer> set1 = new HashSet<Integer>();
Set<Integer> set2 = new HashSet<Integer>();
for(int i = 0; i < n; i++) {
if(set1.contains(sarr)) continue;
if(set2.contains(sarr)) continue;
int comp1 = b - sarr[i];
if(present.contains(comp1)) {
set2.add(sarr[i]);
set2.add(comp1);
present.remove(comp1);
} else {
int comp2 = a - sarr[i];
if(present.contains(comp2)) {
set1.add(sarr[i]);
set1.add(comp2);
present.remove(comp2);
} else {
jout.println("NO");
return;
}
}
}
jout.println("YES");
for(int i = 0; i < n; i++) {
if(i != 0) jout.print(' ');
if(rev) jout.print(set2.contains(arr[i])? 0 : 1);
else jout.print(set1.contains(arr[i])? 0 : 1);
}
}
}
class InputReader {
private static final int bufferMaxLength = 1024;
private InputStream in;
private byte[] buffer;
private int currentBufferSize;
private int currentBufferTop;
private static final String tokenizers = " \t\r\f\n";
public InputReader(InputStream stream) {
this.in = stream;
buffer = new byte[bufferMaxLength];
currentBufferSize = 0;
currentBufferTop = 0;
}
private boolean refill() {
try {
this.currentBufferSize = this.in.read(this.buffer);
this.currentBufferTop = 0;
} catch(Exception e) {}
return this.currentBufferSize > 0;
}
private Byte readChar() {
if(currentBufferTop < currentBufferSize) {
return this.buffer[this.currentBufferTop++];
} else {
if(!this.refill()) {
return null;
} else {
return readChar();
}
}
}
public String token() {
StringBuffer tok = new StringBuffer();
Byte first;
while((first = readChar()) != null && (tokenizers.indexOf((char) first.byteValue()) != -1));
if(first == null) return null;
tok.append((char)first.byteValue());
while((first = readChar()) != null && (tokenizers.indexOf((char) first.byteValue()) == -1)) {
tok.append((char)first.byteValue());
}
return tok.toString();
}
public Integer int32() throws NumberFormatException {
String tok = token();
return tok == null? null : Integer.parseInt(tok);
}
}
class OutputWriter {
private final int bufferMaxOut = 1024;
private PrintWriter out;
private StringBuilder output;
private boolean forceFlush = false;
public OutputWriter(OutputStream outStream) {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outStream)));
output = new StringBuilder(2 * bufferMaxOut);
}
public OutputWriter(Writer writer) {
forceFlush = true;
out = new PrintWriter(writer);
output = new StringBuilder(2 * bufferMaxOut);
}
private void autoFlush() {
if(forceFlush || output.length() >= bufferMaxOut) {
flush();
}
}
public void print(Object... tokens) {
for(int i = 0; i < tokens.length; i++) {
if(i != 0) output.append(' ');
output.append(tokens[i]);
}
autoFlush();
}
public void println(Object... tokens) {
print(tokens);
output.append('\n');
autoFlush();
}
public void flush() {
out.print(output);
output.setLength(0);
}
public void close() {
flush();
out.close();
}
}
| linear | 468_B. Two Sets | CODEFORCES |
import java.io.*;
import java.util.*;
public class CF_468B {
public static void main(String[] args) throws IOException {
new CF_468B().solve();
}
int root(int[] father, int a){
if (father[a]==a) return a;
else return father[a]=root(father, father[a]);
}
void unite(int[] father, int a, int b){
father[root(father, a)]=root(father, b);
}
private void solve() throws IOException{
InputStream in = System.in;
PrintStream out = System.out;
// in = new FileInputStream("in.txt");
// out = new PrintStream("out.txt");
long mod=1_000_000_007;
Scanner sc=new Scanner(in);
int n=sc.nextInt();
long a=sc.nextLong(), b=sc.nextLong();
int[] father=new int[n];
long[] p=new long[n];
HashMap<Long, Integer> pos=new HashMap<Long, Integer>();
for (int i=0;i<n;i++){
father[i]=i;
p[i]=sc.nextLong();
pos.put(p[i],i);
}
for (int i=0;i<n;i++){
if (pos.containsKey(a-p[i])) unite(father,i,pos.get(a-p[i]) );
if (pos.containsKey(b-p[i])) unite(father,i,pos.get(b-p[i]) );
}
boolean[] canA=new boolean[n],
canB=new boolean[n];
Arrays.fill(canA,true);
Arrays.fill(canB,true);
for (int i=0;i<n;i++){
if (!pos.containsKey(a-p[i]) ||
root(father, i)!=root(father, pos.get(a-p[i])))
canA[root(father, i)]=false;
if (!pos.containsKey(b-p[i]) ||
root(father, i)!=root(father, pos.get(b-p[i])))
canB[root(father, i)]=false;
if (!canA[root(father,i)] && !canB[root(father,i)]){
out.println("NO");
return;
}
}
out.println("YES");
for (int i=0;i<n;i++)
if (canA[root(father, i)])
out.print("0 ");
else
out.print("1 ");
}
}
| linear | 468_B. Two Sets | CODEFORCES |
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.HashMap;
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;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
int a = in.nextInt();
int b = in.nextInt();
List<Clause> clauses = new ArrayList<Clause>();
int[] p = new int[n];
Map<Integer, Integer> id = new HashMap<>();
for (int i = 0; i < n; i++) {
p[i] = in.nextInt();
id.put(p[i], i);
}
// var[i] = true means p[i] \in A
for (int i = 0; i < n; i++) {
int x = p[i];
Integer j = id.get(a - x);
if (j == null) {
// var[i] is false
clauses.add(new Clause(i, i, true, false));
} else {
clauses.add(new Clause(i, j, true, true));
clauses.add(new Clause(j, i, false, false));
}
j = id.get(b - x);
if (j == null) {
// var[i] is true
clauses.add(new Clause(i, i, false, true));
} else {
clauses.add(new Clause(i, j, false, false));
clauses.add(new Clause(j, i, true, true));
}
}
SAT2Solver solver = new SAT2Solver(n);
if (!solver.solve(clauses)) {
out.println("NO");
return;
}
out.println("YES");
for (int i = 0; i < n; i++) {
if (i > 0) {
out.print(" ");
}
if (solver.isTrue[i]) {
out.print(0);
} else {
out.print(1);
}
}
out.println();
}
class Clause {
int v1, v2;
boolean neg1, neg2;
// Example: (x=>!y) is translated to Clause(x, y, true, false)
Clause(int v1, int v2, boolean pos1, boolean pos2) {
this.v1 = v1;
this.v2 = v2;
this.neg1 = !pos1;
this.neg2 = !pos2;
}
}
class SAT2Solver {
List<Integer>[] g;
boolean[] isTrue;
int n;
int numComps;
int[] low;
int[] vis;
int[] comp;
boolean[] onStack;
int[] stack;
int sp;
int globalTime;
SAT2Solver(int n) {
this.n = n;
isTrue = new boolean[2 * n];
vis = new int[2 * n];
low = new int[2 * n];
stack = new int[2 * n];
comp = new int[2 * n];
onStack = new boolean[2 * n];
g = new List[2 * n];
}
public boolean solve(List<Clause> clauses) {
for (int i = 0; i < 2 * n; i++) {
g[i] = new ArrayList<Integer>();
}
for (Clause clause : clauses) {
int v1 = clause.v1;
int v2 = clause.v2;
boolean neg1 = clause.neg1;
boolean neg2 = clause.neg2;
if (neg1) {
v1 = negate(v1);
}
if (neg2) {
v2 = negate(v2);
}
//g[negate(v1, n)].add(v2);
//g[negate(v2, n)].add(v1);
g[v1].add(v2);
}
Arrays.fill(vis, -1);
Arrays.fill(onStack, false);
sp = 0;
globalTime = 0;
numComps = 0;
for (int i = 0; i < 2 * n; i++) {
if (vis[i] < 0) {
dfsTarjan(i);
}
}
int[] firstInComp = new int[numComps];
Arrays.fill(firstInComp, -1);
int[] nextSameComp = new int[2 * n];
for (int i = 0; i < 2 * n; i++) {
int c = comp[i];
nextSameComp[i] = firstInComp[c];
firstInComp[c] = i;
}
List<Integer>[] invertedCompEdges = new List[numComps];
for (int i = 0; i < numComps; i++) {
invertedCompEdges[i] = new ArrayList<Integer>();
}
for (int i = 0; i < 2*n; i++) {
for (int j : g[i]) {
invertedCompEdges[comp[j]].add(comp[i]);
}
}
boolean[] compIsTrue = new boolean[numComps];
Arrays.fill(compIsTrue, true);
for (int c = 0; c < numComps; c++) {
if (!compIsTrue[c]) {
continue;
}
for (int i = firstInComp[c]; i >= 0; i = nextSameComp[i]) {
int nc = comp[negate(i)];
if (c == nc) {
return false;
}
}
for (int i = firstInComp[c]; i >= 0; i = nextSameComp[i]) {
int nc = comp[negate(i)];
dfsReject(nc, invertedCompEdges, compIsTrue);
}
}
for (int i = 0; i < 2 * n; i++) {
isTrue[i] = compIsTrue[comp[i]];
}
for (int i = 0; i < n; i++) {
if (isTrue[i] && isTrue[negate(i)]) {
throw new AssertionError();
}
if (!isTrue[i] && !isTrue[negate(i)]) {
return false;
}
}
return true;
}
private int negate(int i) {
return i + (i < n ? n : -n);
}
private void dfsReject(int c, List<Integer>[] invertedCompEdges, boolean[] compIsTrue) {
if (!compIsTrue[c]) {
return;
}
compIsTrue[c] = false;
for (int p : invertedCompEdges[c]) {
dfsReject(p, invertedCompEdges, compIsTrue);
}
}
void dfsTarjan(int v) {
vis[v] = globalTime;
low[v] = globalTime;
++globalTime;
stack[sp++] = v;
onStack[v] = true;
for (int u : g[v]) {
if (vis[u] < 0) {
dfsTarjan(u);
if (low[v] > low[u]) {
low[v] = low[u];
}
} else if (onStack[u] && low[v] > vis[u]) {
low[v] = vis[u];
}
}
if (low[v] == vis[v]) {
while (true) {
int u = stack[--sp];
onStack[u] = false;
comp[u] = numComps;
if (u == v) {
break;
}
}
++numComps;
}
}
}
}
class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
String rl = in.readLine();
if (rl == null) {
return null;
}
st = new StringTokenizer(rl);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
| linear | 468_B. Two Sets | CODEFORCES |
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedInputStream(System.in));
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(System.out)));
while (in.hasNext()) {
int n = in.nextInt(), a = in.nextInt(), b = in.nextInt(), c = 0;
int[] p = new int[n];
TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
for (int i = 0; i < n; i++) {
p[i] = in.nextInt();
map.put(p[i], i);
}
if (a > b) {
int t = b;
b = a;
a = t;
c = 1;
}
boolean ok = true;
int[] cls = new int[n];
while (ok && map.size() > 0) {
Entry<Integer, Integer> last = map.lastEntry();
int v = last.getKey();
int idx = last.getValue();
if (map.containsKey(a - v)) {
cls[idx] = 0;
cls[map.get(a - v)] = 0;
map.remove(v);
map.remove(a -v);
} else if (map.containsKey(b - v)) {
cls[idx] = 1;
cls[map.get(b - v)] = 1;
map.remove(v);
map.remove(b -v);
} else
ok = false;
}
if (!ok)
System.out.println("NO");
else {
System.out.println("YES");
for (int j = 0; j < cls.length; j++) {
if (j != 0)
System.out.print(" ");
System.out.print(c ^ cls[j]);
}
System.out.println();
}
out.flush();
}
in.close();
}
} | linear | 468_B. Two Sets | CODEFORCES |
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.concurrent.LinkedBlockingDeque;
import javax.swing.border.Border;
public class a {
public static long mod = (long) Math.pow(10, 9) + 7;
public static int k = 0;
private static class node implements Comparable<node> {
int l;
int r;
int index;
int index2;
int buffer;
node(int l, int r, int i, int b, int i2) {
this.l = l;
this.r = r;
index = i;
buffer = b;
index2 = i2;
}
@Override
public int compareTo(node o) {
if (k == 0) {
if (o.l < l)
return 1;
else if (o.l > l)
return -1;
else if (o.buffer != -1) {
return 1;
} else
return -1;
} else if (k == 1) {
if (r != o.r)
return r - o.r;
return o.index - index;
} else if (k == 2) {
return r - o.r;
} else {
if (o.index < index)
return 1;
else
return -1;
}
}
}
// private static class point implements Comparable<point> {
// int l;
// int r;
// int index;
// int buffer;
//
// point(int l, int r, int i, int b) {
// this.l = l;
// this.r = r;
// index = i;
// buffer = b;
//
// }
//
// @Override
// public int compareTo(point o) {
// if (o.l < l)
// return 1;
// else if (o.l > l)
// return -1;
// else if (o.r < r)
// return 1;
// else if (o.r > r)
// return -1;
// return 0;
// }
//
// }
public static class point implements Comparable<point> {
long x;
long y;
point(long x, long y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(point o) {
return (int) (x - o.x);
}
}
public static int ch(long y) {
int r = Long.bitCount(y);
return r;
}
public static int gcd(int x, int y) {
if (y == 0)
return x;
return gcd(y, x % y);
}
public static int min[];
public static int max[];
public static void build(int s, int e, int p, int a[]) {
if (s == e) {
min[p] = a[s];
max[p] = a[s];
return;
}
int mid = (s + e) / 2;
build(s, mid, p * 2, a);
build(mid + 1, e, p * 2 + 1, a);
min[p] = Math.min(min[p * 2], min[p * 2 + 1]);
max[p] = Math.max(max[p * 2], max[p * 2 + 1]);
}
public static int getMin(int s, int e, int p, int from, int to) {
if (s > to || e < from)
return Integer.MAX_VALUE;
if (s >= from && e <= to)
return min[p];
int mid = (s + e) / 2;
int a = getMin(s, mid, p * 2, from, to);
int b = getMin(mid + 1, e, p * 2 + 1, from, to);
return Math.min(a, b);
}
public static int getMax(int s, int e, int p, int from, int to) {
if (s > to || e < from)
return Integer.MIN_VALUE;
if (s >= from && e <= to)
return max[p];
int mid = (s + e) / 2;
int a = getMax(s, mid, p * 2, from, to);
int b = getMax(mid + 1, e, p * 2 + 1, from, to);
return Math.max(a, b);
}
public static boolean ch[];
public static ArrayList<Integer> prime;
public static Queue<Integer> pp;
public static void sieve(int k) {
ch[0] = ch[1] = true;
for (int i = 2; i <= k; i++) {
if (!ch[i]) {
prime.add(i);
pp.add(i);
for (int j = i + i; j <= k; j += i) {
ch[j] = true;
}
}
}
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder qq = new StringBuilder();
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
String y[] = in.readLine().split(" ");
int n = Integer.parseInt(y[0]);
int a = Integer.parseInt(y[1]);
int b = Integer.parseInt(y[2]);
int arr[] = new int[n];
HashMap<Integer, Integer> mp = new HashMap();
y = in.readLine().split(" ");
boolean flag = true;
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(y[i]);
if (arr[i] >= a && arr[i] >= b) {
flag = false;
}
mp.put(arr[i], i);
}
if (!flag) {
System.out.println("NO");
return;
}
boolean ch[] = new boolean[n];
int ans[] = new int[n];
for (int i = 0; i < n; i++) {
int k = i;
while (true&&!ch[k]) {
if (mp.containsKey(a - arr[k]) && !ch[mp.get(a - arr[k])]
&& mp.containsKey(b - arr[k])
&& !ch[mp.get(b - arr[k])]) {
break;
} else if (mp.containsKey(a - arr[k])
&& !ch[mp.get(a - arr[k])]) {
//System.out.println(arr[k]);
ch[k] = true;
ans[k] = 0;
ch[mp.get(a - arr[k])] = true;
ans[mp.get(a - arr[k])] = 0;
int s = b - (a - arr[k]);
if (mp.containsKey(s)) {
k = mp.get(s);
} else
break;
} else if (mp.containsKey(b - arr[k])
&& !ch[mp.get(b - arr[k])]) {
ans[k] = 1;
ans[mp.get(b - arr[k])] = 1;
ch[k] = true;
ch[mp.get(b - arr[k])] = true;
int s = a - (b - arr[k]);
if (mp.containsKey(s)) {
k = mp.get(s);
} else
break;
} else {
// System.out.println(arr[i] + " " + i);
System.out.println("NO");
return;
}
}
}
qq.append("YES\n");
for (int i = 0; i < ans.length; i++) {
qq.append(ans[i] + " ");
}
System.out.println(qq);
}
} | linear | 468_B. Two Sets | 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 Main{
// 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>();
//HashMap<Long,Long> map = new HashMap<Long,Long>();
// static long sum=0;
// 1000000007 (10^9+7)
static int mod = 1000000007;
//static int mod = 1000000009,r=0; ArrayList<Integer> l[]= new ArrayList[n];
// 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 Set<Integer> set = new HashSet<Integer>();p
static ArrayList<Integer> cd[];
static int K=0;
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);
//,a=sc.nextInt(),b=sc.nextInt();
// int n=sc.nextInt(),p[]=new int[n],q[]=new int[n];
//int n=sc.nextInt(),a[]=new int[n],b[]=new int[n];
// int n=sc.nextInt(),m=sc.nextInt(),a=sc.nextInt(),b=sc.nextInt();
// int r=1<<28;
int n=sc.nextInt();//,k=sc.nextInt();
int a=sc.nextInt(),b=sc.nextInt(),d[]=new int[n];
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
ArrayList<Integer> A = new ArrayList<Integer>();
for (int i = 0; i < n ; i++) {
d[i]=sc.nextInt();
map.put(d[i],i );
}
int c=1;
if( a>b ){c--; int x=a; a=b; b=x;}
int r[]=new int[n];
if(a==b){
for (int i = 0; i < n; i++) {
if(d[i]>a || !map.containsKey(a-d[i]) ){System.out.println("NO"); return;}
}
System.out.println("YES");
for (int i = 0; i < n; i++) {System.out.print("1 ");}
System.out.println();
return;
}
sort(d);
for (int j = 0; j < n; j++) {
int i=n-j-1;
int id=map.get(d[i]),idd=-1;
if( id<0)continue;
// db(id,d[i]);
if( d[i]<=a ){
if( map.containsKey(a-d[i]) && 0<=(idd=map.get(a-d[i])) ){
r[id]=r[idd]=(c+1)%2;
map.put(a-d[i], -1);
}
else if( map.containsKey(b-d[i]) && 0<=(idd=map.get(b-d[i])) ){
r[id]=r[idd]=c;
map.put(b-d[i], -1); }
else{ System.out.println("NO"); return; }
}
else{
if( map.containsKey(b-d[i]) && 0<=(idd=map.get(b-d[i])) ){
r[id]=r[idd]=c;
map.put(b-d[i], -1); }
else{ System.out.println("NO"); return; }
}
map.put(d[i], -1);
}
System.out.println("YES");
for (int j = 0; j < n; j++) {
System.out.print(r[j]+" ");
}
System.out.println();
}
static class P implements Comparable<P>{
// implements Comparable<Pair>
int id; long d; ;
P(int id,long d){
this.id=id;
this.d=d;
}
public int compareTo(P x){
return (-x.d+d)>=0?1:-1 ; // ascend long
// return -x.d+d ; // ascend
// return x.d-d ; //descend
}
}
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());
}
} | linear | 468_B. Two Sets | CODEFORCES |
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Stack;
import java.util.StringTokenizer;
public class TwoSets {
static int n, a, b;
static HashSet<Integer> arr = new HashSet<Integer>();
static HashSet<Integer> visited = new HashSet<Integer>();
static HashMap<Integer, Integer> result = new HashMap<Integer, Integer>();
static void dfs(int x, int parent, int len) {
stack.push(x);
visited.add(x);
int children = 0;
if (a - x > 0) {
if (a - x != parent && arr.contains(a - x)) {
dfs(a - x, x, len + 1);
children++;
}
}
if (b - x > 0) {
if (b - x != parent && arr.contains(b - x)) {
dfs(b - x, x, len + 1);
children++;
}
}
if (children == 0) {
if (len % 2 == 1) {
System.out.println("NO");
System.exit(0);
} else {
while (!stack.isEmpty()) {
int first = stack.pop();
int second = stack.pop();
if (first == a - second) {
result.put(first, 0);
result.put(second, 0);
} else {
result.put(first, 1);
result.put(second, 1);
}
}
}
}
}
static Stack<Integer> stack = new Stack<Integer>();
public static void main(String[] args) {
InputReader r = new InputReader(System.in);
n = r.nextInt();
a = r.nextInt();
b = r.nextInt();
int[] list = new int[n];
for (int i = 0; i < n; i++) {
list[i] = r.nextInt();
arr.add(list[i]);
}
for (int x : arr) {
if (!visited.contains(x)) {
if (arr.contains(a - x) && arr.contains(b - x))
continue;
if (arr.contains(a - x) || arr.contains(b - x)) {
dfs(x, -1, 1);
} else {
System.out.println("NO");
System.exit(0);
}
}
}
PrintWriter out = new PrintWriter(System.out);
out.println("YES");
for (int i = 0; i < list.length; i++) {
if (result.get(list[i]) == null)
out.println(0);
else
out.println(result.get(list[i]));
}
out.close();
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public InputReader(FileReader stream) {
reader = new BufferedReader(stream);
tokenizer = null;
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| linear | 468_B. Two Sets | CODEFORCES |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.StringTokenizer;
import static java.lang.Integer.*;
public class BDiv1 {
static int n;
static int a;
static int b;
static HashMap<Integer,Integer> graphA=new HashMap<>();
static HashMap<Integer,Integer> graphB=new HashMap<>();
static int [] array;
static int [] original;
static boolean x=true;
public static void main(String[] args) throws Exception{
BufferedReader buf =new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st =new StringTokenizer(buf.readLine());
n=parseInt(st.nextToken());
a=parseInt(st.nextToken());
b=parseInt(st.nextToken());
st =new StringTokenizer(buf.readLine());
array=new int[n];
original=new int [n];
for (int i=0;i<n;i++){
array[i]=parseInt(st.nextToken());
original[i]=array[i];
}
Arrays.sort(array);
for (int i=0;i<n;i++){
int k= Arrays.binarySearch(array,a-array[i]);
if (k>=0){
graphA.put(array[i],array[k]);
graphA.put(array[k],array[i]);
}
}
for (int i=0;i<n;i++){
int k= Arrays.binarySearch(array,b-array[i]);
if (k>=0){
graphB.put(array[i],array[k]);
graphB.put(array[k],array[i]);
}
}
for (int i=0;i<n;i++){
Integer j=graphA.get(array[i]);
if (j!=null){
if (graphB.containsKey(array[i]) && graphB.containsKey(j)){
graphA.remove(array[i]);
graphA.remove(j);
}
else if (graphB.containsKey(array[i]) && !graphB.containsKey(j)){
graphB.remove(graphB.get(array[i]));
graphB.remove(array[i]);
}
else if (!graphB.containsKey(array[i]) && graphB.containsKey(j)){
graphB.remove(graphB.get(j));
graphB.remove(j);
}
}
}
int [] res=new int [n];
for (int i=0;i<n;i++){
if (graphA.containsKey(original[i]))res[i]=0;
else if (graphB.containsKey(original[i])) res[i]=1;
else {
System.out.println("NO");
return;
}
}
System.out.println("YES");
for (int k:res)System.out.print(k+" ");
}
}
| linear | 468_B. Two Sets | CODEFORCES |
import java.util.*;
import java.io.*;
public class Main
{
static HashMap<Integer,Integer> hm;
static int[] array;
static boolean marked[];
static int a , b ;
static int[] ans ;
public static void main( String args[])
{
Scanner sc = new Scanner(System.in);
int n ;
n = sc.nextInt();
a = sc.nextInt();
b = sc.nextInt();
hm = new HashMap<Integer,Integer>();
array = new int[n];
marked = new boolean[n];
for( int i = 0 ; i < n ; ++i )
{
array[i] = sc.nextInt();
hm.put( array[i] , i );
}
if( a == b)
{
boolean flag = true ;
for( int i = 0 ; i < n ; ++i )
if( !hm.containsKey( a - array[i]))
flag = false;
if( !flag)
System.out.println( "NO");
else
{
System.out.println("YES");
for( int i = 0 ; i < n ; ++i)
System.out.print("0 ");
}
}
else
{
ans = new int[n];
for( int i = 0 ; i < n ; ++i )
if( marked[i] ) continue;
else // hadle odd , even and single self loops
{
if( hm.containsKey(a - array[i]) && !hm.containsKey(b - array[i]))
{
propagateA(i);
}
else if( !hm.containsKey(a - array[i]) && hm.containsKey(b - array[i]))
{
// propagate b
propagateB(i);
}
else if(!hm.containsKey(a - array[i]) && !hm.containsKey(b - array[i]))
{
System.out.println("NO");
System.exit(0);
}
}
for( int i = 0 ; i < n ; ++i )
if( marked[i] ) continue;
else // handle doule self loops , cycles
{
start(i);
}
System.out.println("YES");
for( int i = 0 ; i < n; ++i)
System.out.print(ans[i] + " ");
System.exit(0);
}
}
static void propagateA(int index)
{
int i = index;
while( !marked[i])
{
if( hm.containsKey( a - array[i]) && !marked[ hm.get( a - array[i])])
{
marked[i] = true ;
ans [i] = 0 ;
i = hm.get( a - array[i]);
marked[i] = true ;
ans [i] = 0 ;
if( hm.containsKey( b - array[i]) && !marked[ hm.get( b - array[i])])
{
i = hm.get( b - array[i]);
}
}
else
{
System.out.println("NO");
System.exit(0);
}
}
}
static void propagateB(int index)
{
int i = index;
while( !marked[i])
{
if( hm.containsKey( b - array[i]) && !marked[ hm.get( b - array[i])])
{
marked[i] = true ;
ans [i] = 1 ;
i = hm.get( b - array[i]);
marked[i] = true ;
ans [i] = 1 ;
if( hm.containsKey( a - array[i]) && !marked[ hm.get( a - array[i])])
{
i = hm.get( a - array[i]);
}
}
else
{
System.out.println("NO");
System.exit(0);
}
}
}
static void start(int index)
{
int i = index ;
while( !marked[i] )
{
//System.out.println( a - array[i]);
if(!marked[ hm.get( a - array[i])])
{
marked[i] = true ;
ans [i] = 0 ;
i = hm.get( a - array[i]);
marked[i] = true ;
ans [i] = 0 ;
i = hm.get( b - array[i]);
}
}
}
} | linear | 468_B. Two Sets | CODEFORCES |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class B {
static Set<Integer> A;
static Set<Integer> B;
static TreeSet<Integer> ts;
static int a;
static int b;
static boolean noAns;
public static void main(String[] args) throws Exception{
int n = readInt();
a = readInt();
b = readInt();
ts = new TreeSet<Integer>();
int[] table = new int[n];
for(int i = 0; i<n; i++){
table[i] = readInt();
ts.add(table[i]);
}
A = new HashSet<Integer>();
B = new HashSet<Integer>();
noAns = false;
for(Integer cur:ts){
boolean fitsA = false;
boolean fitsB = false;
if(A.contains(cur) || B.contains(cur)){
continue;
}
if(ts.contains(a-cur)){
fitsA = true;
}
if(ts.contains(b-cur)){
fitsB = true;
}
if(fitsA && fitsB){
continue;
}
else if(!(fitsA || fitsB)){
noAns = true;
}
else if(fitsA){
tour(cur, false);
}
else if(fitsB){
tour(cur, true);
}
}
for(Integer cur:ts){
if(A.contains(cur) || B.contains(cur)){
continue;
}
else{
A.add(cur);
}
}
if(!noAns){
System.out.println("YES");
StringBuilder sb = new StringBuilder();
for(int i = 0; i< n; i++){
if(A.contains(table[i])){
sb.append("0");
}
else{
sb.append("1");
}
sb.append(" ");
}
System.out.println(sb);
}
else{
System.out.println("NO");
}
}
static void tour(Integer cur, boolean bb){
if(A.contains(cur) || B.contains(cur)){
return;
}
if(bb){
B.add(cur);
B.add(b-cur);
if(ts.contains(a-cur)){
B.add(a-cur);
if(ts.contains(b-(a-cur))){
tour(b-(a-cur), true);
}
else{
noAns = true;
}
}
if(ts.contains(a-(b-cur))){
B.add(a-(b-cur));
if(ts.contains(b-(a-(b-cur)))){
tour(b-(a-(b-cur)), true);
}
else{
noAns = true;
}
}
}
else{
A.add(cur);
A.add(a-cur);
if(ts.contains(b-cur)){
A.add(b-cur);
if(ts.contains(a-(b-cur))){
tour(a-(b-cur), false);
}
else{
noAns = true;
}
}
if(ts.contains(b-(a-cur))){
A.add(b-(a-cur));
if(ts.contains(a-(b-(a-cur)))){
tour(a-(b-(a-cur)), false);
}
else{
noAns = true;
}
}
}
}
static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st = new StringTokenizer(" ");
static String readString() throws Exception{
while(!st.hasMoreTokens()){
st = new StringTokenizer(stdin.readLine());
}
return st.nextToken();
}
static int readInt() throws Exception {
return Integer.parseInt(readString());
}
static long readLong() throws Exception {
return Long.parseLong(readString());
}
}
| linear | 468_B. Two Sets | CODEFORCES |
import java.text.DecimalFormat;
import java.io.*;
import java.util.*;
import java.lang.reflect.Array;
/**
* @author Mukesh Singh
*
*/
public class AB {
private InputStream input;
private PrintStream output;
private Scanner inputSc;
public AB(InputStream input, PrintStream output) {
this.input = input;
this.output = output;
init();
}
private void init() {
inputSc = new Scanner(input);
}
static int lineToInt(String line) {
return Integer.parseInt(line);
}
static long lineToLong(String line) {
return Long.parseLong(line);
}
static double lineToDouble(String line) {
return Double.parseDouble(line);
}
public void solve()
{
solveTestCase();
}
/**
* @define global / instance variables
*/
HashMap<Integer,Integer> mat ;
long dist[] ;
int vec[] ;
int ar[] ;
Set<Integer> st ;
boolean isDone[] ;
final long INF = 100000000000000000L ;
/**
* @solve test case
*/
@SuppressWarnings("unchecked")
private void solveTestCase()
{
int i , j , k , n , m , d , l ,b , p , q , r;
long N , M, K;
int x1 , y1 , x2 , y2 ,x;
int a1,a2,b1,b2,a ;
DecimalFormat df = new DecimalFormat("#,###,##0.00");
String str = inputSc.nextLine();
String delims = "[ ]+";
String tokens[] = str.split(delims);
n = lineToInt(tokens[0]);
a = lineToInt(tokens[1]);
b = lineToInt(tokens[2]);
mat = new HashMap<Integer,Integer>() ;
st = new TreeSet<Integer>();
ar = new int[n+4] ;
vec = new int[n+4] ;
str = inputSc.nextLine();
tokens = str.split(delims);
for( i = 1 ; i <= n ; i++ )
{
ar[i] = lineToInt(tokens[i-1]);
mat.put(ar[i],i) ;
st.add(ar[i]);
vec[i] = i ;
}
vec[n+1] = n+1 ;
vec[n+2] = n+2 ;
for( i = 1 ; i <= n ; i++ )
{
x= ar[i];
if(st.contains(a-x))
{
Bing(mat.get(x),mat.get(a-x));
}
else
Bing(n+1 , mat.get(x));
if(st.contains(b-x))
{
Bing(mat.get(x),mat.get(b-x));
}
else
Bing(n+2 , mat.get(x));
}
if(find(n+1)==find(n+2))
{
output.println("NO");
return ;
}
output.println("YES");
for( i =1 ; i<= n ; i ++ )
{
if(find(i)==find(n+1))
output.print("1 ");
else
output.print("0 ");
}
output.println();
}
int find(int x)
{
if(x==vec[x]) return x;
return vec[x]=find(vec[x]);
}
void Bing(int a,int b)
{
int A=find(a);int B=find(b);
if(A==B) return ;
vec[B]=A;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
FileInputStream in = null;
FileOutputStream out = null;
PrintStream ps = null ;
InputStream is = null ;
try
{
is = new FileInputStream("file.in");
out = new FileOutputStream("file.out");
ps = new PrintStream(out);
}
catch ( Exception e )
{}
AB sd = new AB(System.in, System.out);
sd.solve();
try
{
if (is != null)
{
is.close();
}
if (out != null) {
out.close();
}
if (ps != null) {
ps.close();
}
}catch (Exception e){}
//SquareDetector sd = new SquareDetector(System.in, System.out);
//sd.solve();
}
}
| linear | 468_B. Two Sets | CODEFORCES |
import java.util.*;
import java.io.*;
public class B {
public static PrintStream out = System.out;
public static InputReader in = new InputReader(System.in);
static class Node implements Comparable<Node> {
int res;
Node(int pp) {
p = pp;
}
int p;
@Override
public int compareTo(Node n) {
return Integer.compare(p, n.p);
}
@Override
public boolean equals(Object o) {
return p == ((Node) o).p;
}
}
public static void main(String args[]) {
int N, a, b;
N = in.nextInt();
int[] label;
a = in.nextInt();
b = in.nextInt();
if (a < b) {
label = new int[] {0, 1};
} else {
int tmp = a;
a = b;
b = tmp;
label = new int[] {1, 0};
}
Node[] nodes = new Node[N];
for (int i = 0; i < N; i++) {
nodes[i] = new Node(in.nextInt());
}
TreeSet<Node> ts = new TreeSet<>();
for (int i = 0; i < N; i++) {
ts.add(nodes[i]);
}
while (!ts.isEmpty()) {
Node n = ts.first();
Node an = new Node(a - n.p);
Node bn = new Node(b - n.p);
SortedSet<Node> ats = ts.tailSet(an);
SortedSet<Node> bts = ts.tailSet(bn);
Node an2 = ats.isEmpty() ? null : ats.first();
Node bn2 = bts.isEmpty() ? null : bts.first();
Node n2 = null;
int l = 0;
if (bn2 != null && bn2.equals(bn)) {
n2 = bn2;
l = label[1];
} else if (an2 != null && an2.equals(an)) {
n2 = an2;
l = label[0];
} else {
NO();
}
if (!n.equals(n2)) {
ts.remove(n);
n.res = l;
}
ts.remove(n2);
n2.res = l;
}
out.println("YES");
for (int i = 0; i < nodes.length; i++) {
if (i != 0) out.print(" ");
out.print(nodes[i].res);
}
out.println();
}
static void NO() {
out.println("NO");
System.exit(0);
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
}
| linear | 468_B. Two Sets | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class ProblemB3 {
Map<Integer, List<int[]>> dest;
private ProblemB3() throws IOException {
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
String h = rd.readLine();
String[] q = h.split("\\s+");
int a = Integer.parseInt(q[1]);
int b = Integer.parseInt(q[2]);
h = rd.readLine();
q = h.split(" ");
int n = q.length;
int[] p = new int[n];
for(int i=0;i<n;i++) {
p[i] = Integer.parseInt(q[i]);
}
Set<Integer> pset = new HashSet<>();
for(int x: p) {
pset.add(x);
}
dest = new HashMap<>();
boolean res = true;
for(int x: p) {
boolean aOk = pset.contains(a-x);
boolean bOk = pset.contains(b-x);
if(!aOk && !bOk) {
res = false;
break;
} else {
if(aOk) {
addEdgeAndBack(x,a-x,0);
}
if(bOk) {
addEdgeAndBack(x,b-x,1);
}
}
}
Set<Integer> aSet = new HashSet<>();
if(res && a != b) {
for(int x: p) {
List<int[]> e = getEdges(x);
if(e.size() == 1) {
int[] edge = e.get(0);
boolean odd = true;
int curA = edge[1];
int prev = x;
while(true) {
int cur = edge[0];
if(curA == 0 && odd) {
aSet.add(prev);
aSet.add(cur);
}
e = getEdges(cur);
if(e.size() == 1) {
if(!odd && e.get(0)[0] != cur) {
res = false;
}
break;
}
int other = e.get(0)[0] == prev?1:0;
edge = e.get(other);
if(edge[1] == curA) {
res = false;
break;
}
curA = 1-curA;
prev = cur;
odd = !odd;
}
if(!res) {
break;
}
}
}
}
out(res?"YES":"NO");
if(res) {
StringBuilder buf = new StringBuilder();
for(int i=0;i<n;i++) {
if(i>0) {
buf.append(' ');
}
buf.append(aSet.contains(p[i])?'0':'1');
}
out(buf);
}
}
private void addEdgeAndBack(int from, int to, int u) {
addEdge(from, to, u);
addEdge(to, from, u);
}
private void addEdge(int from, int to, int u) {
List<int[]> edges = getEdges(from);
for(int[] edge: edges) {
if(edge[0] == to) {
return;
}
}
edges.add(new int[]{to, u});
}
private List<int[]> getEdges(int from) {
List<int[]> ds = dest.get(from);
if(ds == null) {
ds = new ArrayList<>();
dest.put(from, ds);
}
return ds;
}
private static void out(Object x) {
System.out.println(x);
}
public static void main(String[] args) throws IOException {
new ProblemB3();
}
}
| linear | 468_B. Two Sets | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class B {
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter out;
public void solve() throws IOException {
int N = nextInt();
int A = nextInt();
int B = nextInt();
int[] nsA = new int[N];
int[] nsB = new int[N];
char[] ans = new char[N];
Arrays.fill(nsA, -1);
Arrays.fill(nsB, -1);
Arrays.fill(ans, 'C');
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int[] P = new int[N];
for (int i = 0; i < N; i++) {
P[i] = nextInt();
map.put(P[i], i);
}
// if A == B
if (A == B) {
for (int i = 0; i < N; i++) {
if (!map.containsKey(A - P[i])) {
out.println("NO"); return;
}
}
out.println("YES");
for (int i = 0; i < N; i++) {
out.print(0 + " ");
}
out.println();
return;
}
for (int i = 0; i < N; i++) {
int oppA = A - P[i];
int oppB = B - P[i];
if (map.containsKey(oppA)) {
nsA[i] = map.get(oppA);
}
if (map.containsKey(oppB)) {
nsB[i] = map.get(oppB);
}
}
for (int i = 0; i < N; i++) {
if (nsA[i] == -1 && nsB[i] == -1) {
out.println("NO");
return;
}
}
for (int i = 0; i < N; i++) {
if (ans[i] != 'C') continue;
if (nsA[i] == -1) {
if (!go(i, 'B', ans, nsA, nsB) ){
out.println("NO"); return;
}
} else if (nsB[i] == -1) {
if (!go(i, 'A', ans, nsA, nsB) ){
out.println("NO"); return;
}
}
}
for (int i = 0; i < N; i++) {
if (ans[i] != 'C') continue;
if (nsA[i] == i || nsB[i] == i) {
if (nsA[i] == i) {
if (!go(i, 'B', ans, nsA, nsB) ){
out.println("NO"); return;
}
} else {
if (!go(i, 'A', ans, nsA, nsB) ){
out.println("NO"); return;
}
}
}
}
for (int i = 0; i < N; i++) {
if (ans[i] != 'C') continue;
if (!go(i, 'A', ans, nsA, nsB) ){
out.println("NO"); return;
}
}
for (int i = 0; i < N; i++) {
if (ans[i] == 'C') {
out.println("NO");
return;
}
}
out.println("YES");
for (int i = 0; i < N; i++) {
out.print(ans[i] == 'A'? 0: 1);
out.print(" ");
}
out.println();
}
public boolean go(int cur, char link, char[] ans, int[] nsA, int[] nsB) {
while (ans[cur] == 'C') {
int next = link == 'A'? nsA[cur]: nsB[cur];
if (next == -1) return false;
if (ans[next] != 'C') return false;
ans[cur] = link;
ans[next] = link;
int nextNext = link == 'A'? nsB[next]: nsA[next];
cur = nextNext;
if (cur == -1) return true;
}
return true;
}
/**
* @param args
*/
public static void main(String[] args) {
new B().run();
}
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
out = new PrintWriter(System.out);
solve();
reader.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
| linear | 468_B. Two Sets | CODEFORCES |
import java.io.*;
import java.util.*;
public class Main {
static BufferedReader reader;
static StringTokenizer tokenizer;
static PrintWriter writer;
static int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextToken());
}
static long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(nextToken());
}
static double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(nextToken());
}
static String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
public static void main(String[] args) throws IOException {
reader = new BufferedReader(new InputStreamReader(System.in));
writer = new PrintWriter(System.out);
pineapple();
reader.close();
writer.close();
}
static void pineapple() throws NumberFormatException, IOException {
int n = nextInt();
int a = nextInt();
int b = nextInt();
TreeSet<Integer> al = new TreeSet<Integer>();
TreeMap<Integer, Integer> mp = new TreeMap<Integer, Integer>();
int[] ans = new int[n];
Arrays.fill(ans, -1);
TreeSet<Integer> used = new TreeSet<Integer>();
int[] mas = new int[n];
for (int i = 0; i < n; i++) {
int t = nextInt();
al.add(t);
mas[i] = t;
mp.put(t, i);
}
for (int st : al) {
if (used.contains(st))
continue;
{
int pr = st;
int cc = -1;
TreeSet<Integer> u2 = new TreeSet<Integer>();
u2.add(pr);
if (al.contains(a - pr) && !u2.contains(a - pr))
cc = a - pr;
else if (al.contains(b - pr) && !u2.contains(a - pr))
cc = b - pr;
if (cc != -1) {
u2.add(cc);
boolean bGo = true;
while (bGo) {
bGo = false;
int nxt = -1;
if (al.contains(a - cc) && !u2.contains(a - cc))
nxt = a - cc;
else if (al.contains(b - cc) && !u2.contains(b - cc))
nxt = b - cc;
if (nxt != -1) {
bGo = true;
u2.add(nxt);
cc = nxt;
pr = cc;
}
}
st = cc;
}
}
int x = st;
while (x != -1) {
int curr = x;
used.add(curr);
x = -1;
int next1 = a - curr;
if (al.contains(next1)) {
if (!used.contains(next1)) {
x = next1;
int ci = mp.get(curr);
int ni = mp.get(next1);
if (ans[ci] == -1 && ans[ni] == -1) {
ans[ni] = 0;
ans[ci] = 0;
}
}
}
int next2 = b - curr;
if (al.contains(next2)) {
if (!used.contains(next2)) {
x = next2;
int ci = mp.get(curr);
int ni = mp.get(next2);
if (ans[ci] == -1 && ans[ni] == -1) {
ans[ni] = 1;
ans[ci] = 1;
}
}
}
}
}
for (int i = 0; i < n; i++) {
if (ans[i] == -1) {
if (2 * mas[i] == a) {
ans[i] = 0;
continue;
}
if (2 * mas[i] == b) {
ans[i] = 1;
continue;
}
writer.println("NO");
return;
}
}
writer.println("YES");
for (int i = 0; i < n; i++) {
writer.print(ans[i] + " ");
}
}
} | linear | 468_B. Two Sets | CODEFORCES |