Codeforces Round #496 (Div. 3) 解題報告 D. Polycarp and Div 3 DP 數字理論

http://codeforces.com/contest/1005/problem/D

解題思路:

1.能被3整除的單個數字(0,3,6,9……)

2.對3取模的數字做兩個計數器,當餘數1的個數或餘數2的個數出現連續三個時

3.當餘數1和2的個數各有一個

4.滿足以上三種情況則令目標計數器+1,然後把兩個餘數計數器清零重新計算

import java.util.Scanner;

public class Main {

    public static void main(String args[]) {

        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        int cnt = 0,x1 = 0,x2 = 0;
        for(int i = 0;i < str.length();i++) {
            if((str.charAt(i) - 48) % 3 == 0) {
                cnt++;
                x1 = x2 = 0;
            } else if((str.charAt(i) - 48) % 3 == 1) {
                x1++;
            } else if((str.charAt(i) - 48) % 3 == 2) {
                x2++;
            }
            if(x1 == 3 || x2 == 3 || (x1 >= 1 && x2 >= 1)) {
                cnt++;
                x1 = x2 = 0;
            }
        }
        System.out.println(cnt);
    }
}

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