codeforces 解題報告 1003B. Binary String Constructing 構造

http://codeforces.com/problemset/problem/1003/B

解題思路:

1. a個0,b個1,構造一個有x個相鄰字符不相等的二進制字符串

2.在紙上構造一下就可以發現一個“01”串有一個相鄰字符不相等,每往後增加一個“01”(例如“0101”)就會增加兩個相鄰字符不相等。由於數據保證答案存在,並且01必定至少有一個,那麼我就構造如上的字符串(首先令x+1,修正第一個“01”只有一個相鄰字符不相等的情況)。當構造完x個相鄰不相等字符後,剩餘的01字符分別往串頭和串尾添加不影響相鄰不相等字符數。

3.如上構造後會WA7,因爲還要考慮一個字符1可能比字符0大的情況,考慮臨界狀態,那麼應該以相反情況“10”串的形式構造。

4.我寫的代碼冗餘比較大,但又不知道如何去簡化,煩惱!

import java.util.Scanner;
import java.util.Vector;

public class Main {

    public static void main(String args[]) {

        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt(),b = sc.nextInt(),x = sc.nextInt();
        x++;
        Vector<Integer> v = new Vector<>();
        if(a > b) {
            while (x >= 2) {
                v.add(0);
                v.add(1);
                x -= 2;
                a--;
                b--;
            }
            if (x == 0) {
                for (int i = 0; i < a; i++)
                    System.out.print(0);
            }
            for (int i : v)
                System.out.print(i);
            for (int i = 0; i < b; i++)
                System.out.print(1);
            if(x != 0) {
                for (int i = 0; i < a; i++)
                    System.out.print(0);
            }
        } else {
            while (x >= 2) {
                v.add(1);
                v.add(0);
                x -= 2;
                a--;
                b--;
            }
            if (x == 0) {
                for (int i = 0; i < b; i++)
                    System.out.print(1);
            }
            for (int i : v)
                System.out.print(i);
            for (int i = 0; i < a; i++)
                System.out.print(0);
            if (x != 0) {
                for (int i = 0; i < b; i++)
                    System.out.print(1);
            }
        }
    }
}

發佈了135 篇原創文章 · 獲贊 12 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章