除法
輸入正整數n,按從小到大的順序輸出所有形如 abcde/fghij=n的表達式,其中a~j恰好為數字0~9的一個排列,2<=n<=79。
樣例輸入:
62
樣例輸出:
79546/01283=62
94736/01528=62
如何解決這個問題?
2010-7-16更新
上面的問題讓我一下子想到了如何求一個序列的全排列的問題,于是順著這個思路摸索了一下。Google到了一個算法。
遞歸
例說明如何編寫全排列的遞歸算法。
1、首先看最后兩個數4, 5。 它們的全排列為4 5和5 4, 即以4開頭的5的全排列和以5開頭的4的全排列。由于一個數的全排列就是其本身,從而得到以上結果。
2、再看后三個數3, 4, 5。它們的全排列為3 4 5、3 5 4、 4 3 5、 4 5 3、 5 3 4、 5 4 3 六組數。
即以3開頭的和4,5的全排列的組合、以4開頭的和3,5的全排列的組合和以5開頭的和3,4的全排列的組合.
從而可以推斷,設一組數p = {r1, r2, r3, ... ,rn}, 全排列為perm(p),pn = p - {rn}。
因此perm(p) = r1perm(p1), r2perm(p2), r3perm(p3), ... , rnperm(pn)。當n = 1時perm(p} = r1。
為了更容易理解,將整組數中的所有的數分別與第一個數交換,這樣就總是在處理后n-1個數的全排列。
這兩天都是水題,沒有什么想法而言,就是為了熟悉一下感覺。我又給互聯網上增加了不少垃圾日志。
昨晚出了點突發事件,原定的寫程序事件被用來處理事情了。不過后來我倒是有點想明白了,題目只是很少一點時間在看題目,很忙的時候可以先花幾分鐘把題目弄明白了,然后在去忙別的事情,這種件的空隙還能想一想思路。不知POJ有什么辦法可以把題目批量導出的,我就不用天天費勁上網讀題目了,在單位也能抽空瞅兩眼。
我堅持兩件事情:1。決不直接貼題目的代碼 2。每天都寫題目
POJ 3006
計劃打個表,然后直接搞,看了一下數據很小,應該沒有什么問題。
在這里順便題一下素數篩選法。
以下內容來自Wikipedia:
To find all the prime numbers less than or equal to a given integer n by Eratosthenes' method:
- Create a list of consecutive integers from two to n: (2, 3, 4, ..., n).
- Initially, let p equal 2, the first prime number.
- Strike from the list all multiples of p less than or equal to n. (2p, 3p, 4p, etc.)
- Find the first number remaining on the list after p (this number is the next prime); replace p with this number.
- Repeat steps 3 and 4 until p2 is greater than n.
- All the remaining numbers in the list are prime
后來,歐拉同學提出了另外一個辦法,讓每個數只要標記一次就ok
A) Start with all the natural numbers except '1' which is not a prime:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ...
^
B) The leftmost number is prime. Multiply each number in the list by this prime and
then discard the products:
(4 6 8 10 12 14 16 18 20 22 24 26 28 30 ... )
These are removed:
4 6 8 10 12 14 16 18 20 22 24 26 28 30
These are left:
2 3 5 7 9 11 13 15 17 19 21 23 25 27 29 ...
^
C) The number after the previous prime is also a prime. Multiply by it each number
in the new list starting from this prime and then discard the products:
(9 15 21 27 33 39 45 51 57 63 69 75 81 87 ...)
These are removed:
9 15 21 27
These are left:
2 3 5 7 11 13 17 19 23 25 29 ...
^
=================================================
2010-7-13 23:47
拆掉了自己的惠普V3159筆記本,心情一片大好,竟然裝上以后運行正常了。出來混,遲早要還,之前一直對于拆機器的事情不感興趣,現在可真是被逼得。
我終于可以去中關村賺取那90塊的拆機費了: )
PS:今天中午修好了屋子里面的抽水馬桶,心情一片大好。
1.WA數次,因為邊界的問題,把2也當成候選數了,沒有留心two odd primes.
2.gcc編譯math.h時,需要-lm.
3.如何從vim里面把代碼拷出來提交到POJ的那個框框里面?我搞了半天沒有解決
附:
gcc -l參數
-l參數就是用來指定程序要鏈接的庫,-l參數緊接著就是庫名,那么庫名跟真正的庫文件名有什么關系呢?就拿數學庫來說,他的庫名是m,他的庫文件名是libm.so,很容易看出,把庫文件名的頭lib和尾.so去掉就是庫名了