Uva10862-connect the Cable Wires (recursive + large number of Java)
Topic links
main topic: give you n house in a straight line, and then only give you a cable service, ask each house is connected to wired, the way can be indirect through the House Direct Neighbor connection (if its neighbor to connect Wired), Another is the direct connection to the cable service is also possible.
problem thinking: The back of the house is numbered 1, the front is n, assuming we want to even 1th house, then it has three possibilities.
1, direct and cable service connection, then add f (n-1) species (the front of the n-1 House of the combination of the way).
2, and House No. 2nd are connected to the cable service, then the F (n-1) species.
3, and 2nd House link and connected with cable service, then this means that the 2nd House can not be linked to cable service, otherwise formed ring. In this way, you can think of numbers 1th and 2nd as a whole, and have an edge with the cable service. Such a situation can be divided into two types: (1), not and third, plus F (n-2). (2) and third, so the situation goes back to situation 3, indicating that this is recursive.
So f (n) = 2 f (n-1) + f (n-2) + f (n-3) +: + F (1) + 1. (recursion to 1 only when not connected with the number 1th and the number 1th and then 1th and cable service both)
Also write F (n-1), subtract: f (n) = 3 $*$ f (n-1)-F (n-2); (n > 2).
The boundary f (2) = 3, f (1) = 1;3 2000 will exceed long long, so use a large number.
Code:
Import Java.util.*;import Java.math.*;import java.io.*; Public classMain {StaticBigInteger f[] =Newbiginteger[2005]; Public Static voidInit () {f[1] = biginteger.valueof (1); f[2] = biginteger.valueof (3); for(inti =3; I <= -; i++) F[i] = biginteger.valueof (3). Multiply (F[i-1]). Subtract (F[i-2]); } Public Static voidMain (String args[]) {ScannerCin=NewScanner (system.in);intN Init (); while(true) {n =Cin. Nextint ();if(n = =0) Break; System.out.println (F[n]); } }}
Uva10862-connect the Cable Wires (recursive + large number of Java)