演算法筆記_093:藍橋杯練習 Problem S4: Interesting Numbers 加強版(Java)

來源:互聯網
上載者:User

標籤:form   images   span   演算法   size   ide   res   練習   oid   

目錄

1 問題描述

2 解決方案

 1 問題描述

Problem Description
  We call a number interesting, if and only if:
  1. Its digits consists of only 0, 1, 2 and 3, and all these digits occurred at least once.
  2. Inside this number, all 0s occur before any 1s, and all 2s occur before any 3s.
  Therefore, the smallest interesting number according to our definition is 2013. There are two more interseting number of 4 digits: 2031 and 2301.
  Your task is to calculate the number of interesting numbers of exactly n digits. As the answer might be very large, you only need to output the answer modulo 1000000007.
Input Format
  The input has one line consisting of one positive integer n (4 ≤ n ≤ 10^15).
Output Format
  The output has just one line, containing the number of interesting numbers of exactly n digits, modulo 1000000007.
Input Sample
  4
Output Sample
  3

 2 解決方案

本題主要考查數學組合數推理化簡,具體思考過程如下:

引用自文末參考資料1:

 

推導過程,在草稿紙上推導了一下:

本文下面代碼結果運行為90分,代碼僅供參考,文末參考資料1中代碼運行結果為100分,可以參考一下哦。

具體代碼如下:

import java.util.Scanner;public class Main {    public final static long p = 1000000007L;    //求取a的b次方取餘p的值    public long getPowMod(long a, long b) {        long temp = a, result = 1;        while(b != 0) {            if((b & 1) == 1)                result = result * temp % p;            temp = temp * temp % p;            b >>= 1;        }        return result;    }        public void printResult(long n) {        if(n == 4) {            System.out.println(3);            return;        }        long m = n - 1;        long result = getPowMod(2, m - 2);        m = m % p;        result = result * (m * m % p - 3 * m % p) % p + m;        result %= p;        System.out.println(result);        return;    }        public static void main(String[] args) {        Main test = new Main();        Scanner in = new Scanner(System.in);        long n = in.nextLong();        test.printResult(n);            }}

 

 

 

參考資料:

1. 演算法提高 Problem S4: Interesting Numbers 加強版 解題報告

 

演算法筆記_093:藍橋杯練習 Problem S4: Interesting Numbers 加強版(Java)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.