본문 바로가기

PS/Problems

[Java] Div2) C.And Matching - bitwise, case work

https://codeforces.com/contest/1631/problem/C

 

Problem - C - Codeforces

 

codeforces.com

두 integer n, k가 주어진다. (2는 2의 a제곱, k<n)

0, 1, 2, ... n-2, n-1 의 수들을 2개씩 묶어 n/2의 쌍이 나오면

그 쌍끼리 bitwise and 한 값들의 총합이 k가 나오는 경우를 찾는다.

불가능하면 -1출력

 

case work만 잘 접근했으면 충분히 풀 수 있었을텐데...

k가

0인 경우 

n-1인 경우

그 외의 경우

로 case를 나눈다.

 

임의의 정수 p에 대해

p & (n - p - 1) == 0

이라는 성질을 이용해야한다.

package contest.codeforce_0127;

import java.util.*;
import java.io.*;

public class q3{
    static FastScanner fs = new FastScanner();
    static PrintWriter pw = new PrintWriter(System.out);
    static long t, n, k;
    public static void main(String[] args){
        t = fs.nextLong();
        for (int tt=0;tt<t;tt++){
            n = fs.nextLong();
            k = fs.nextLong();
            solve();
        }
        pw.close();
    }

    static void solve(){
        if (k == n - 1){
            if (n == 4) pw.println(-1);
            else{
                pw.printf("%d %d\n", n - 1, n - 2);
                pw.printf("%d %d\n", n - 3, 1);
                pw.printf("%d %d\n", 2, 0);
                for (long i=3;i<n/2;i++){
                    pw.printf("%d %d\n", i, n - 1 - i);
                }
            }
        }
        else if (k == 0){
            for (long i=0;i<n/2;i++){
                pw.printf("%d %d\n", i, n - 1 - i);
            }
        }
        else{
            pw.printf("%d %d\n", 0, n - k - 1);
            pw.printf("%d %d\n", k, n - 1);
            for (long i=1;i<n/2;i++){
                if (i == k || i == n - k - 1) continue;
                pw.printf("%d %d\n", i, n - 1 - i);
            }
        }

    }

//    ----------input function----------

    static void sort(int[] a){
        ArrayList<Integer> L = new ArrayList<>();
        for (int i : a) L.add(i);
        Collections.sort(L);
        for (int i = 0; i < a.length; i++) a[i] = L.get(i);
    }

    static class FastScanner{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer("");
        String next(){
            while (!st.hasMoreTokens()){
                try{
                    st = new StringTokenizer(br.readLine());
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt(){
            return Integer.parseInt(next());
        }

        int[] readArray(int n){
            int[] a = new int[n];
            for (int i = 0; i < n; i++) a[i] = nextInt();
            return a;
        }

        long nextLong(){
            return Long.parseLong(next());
        }
    }
}