Description: Given a set of N (1≤n≤10) (positive negative), a partitioning method is used to make all partitioned blocks cost and minimize. Each of these tiles costs and minimizes. The cost of each block is the sum of the squares of the numbers within the block.
Analysis: Because you see the maximum of n is 10, you can use the state to compress the DP, the maximum complexity of O (2^10*2^10)
Set Dp[i] Indicates the minimum cost and the time when the state is I.
Can be launched dp[x] = min (Dp[y] + dp[z] | Y∪z = X && y∩z =∅}
Initial time dp[x] = Sum{a[i] | I}^2 in the X collection.
So you can write
1#include <iostream>2#include <cstring>3#include <cstdio>4#include <string>5#include <algorithm>6 using namespacestd;7 intN;8 #defineINF 0x3f3f3f9 inta[ One];Ten intdp[1030]; One intMain () { A while(cin>>N) { - for(inti =1; I <= N; i++){ -scanf"%d", &a[i]); the } - for(inti =0; I < (1<<Ten); i++){ - intsum =0; - inttemp =i; + intCO =1; - while(temp!=0){ + intx = temp&1; A if(x = =1){ atSum + =A[co]; - } -co++; -temp = temp/2; - } -Dp[i] = sum*sum; in } - to for(inti =0; I < (1<<N); i++){ + for(intj =0; J < I; J + +){ - if((i&j) = =0){//There are no coincident elements. theDp[i|j] = min (dp[i|j], dp[i]+Dp[j]); * } $ }Panax Notoginseng } -cout<<dp[(1<<n)-1]<<Endl; the + } A the return 0; +}
However, the algorithm can be further optimized.
Z can be expressed as y^x,y belongs to X can be represented (y&x) = Y.
So can be written as dp[x] = min (Dp[y] + dp[x^y] | X&y=y])
Optimization to O (3^n algorithm) when enumerating
for (y = (x-1) &x; y > 0; y = (y-1) &x)
Because (x-1) &x means that the first bit of x 1 is changed to 0.
1#include <iostream>2#include <cstring>3#include <cstdio>4#include <string>5#include <algorithm>6 using namespacestd;7 intN;8 #defineINF 0x3f3f3f9 inta[ One];Ten intdp[1030]; One intMain () { A while(cin>>N) { - for(inti =1; I <= N; i++){ -scanf"%d", &a[i]); the } - for(inti =0; I < (1<<Ten); i++){ - intsum =0; - inttemp =i; + intCO =1; - while(temp!=0){ + intx = temp&1; A if(x = =1){ atSum + =A[co]; - } -co++; -temp = temp/2; - } -Dp[i] = sum*sum; in } - to for(inti =0; I < (1<<N); i++){ + for(intj = (i1) &i; J>0; j = (J-1) &i) { -Dp[i] = min (Dp[i], dp[j]+dp[i^J]); the * } $ }Panax Notoginsengcout<<dp[(1<<n)-1]<<Endl; - the } + A return 0; the}
Some knowledge of state compression bit operation
Shift left: 1<<x, which moves the 1 to the left X-bit.
X<<1, which means to move each bit of x 1 bits to the left. (as by 2) the right side is not enough to add 0.
The right shift is similar.
Gets the value of one or more fixed bits
x& (1<<J) represents the value of getting X j-1 bits from the right number.
Set the position of one or more fixed bits to 0.
x& (~ (1<<J))
The inverse is used in XOR or
x& (x-1) indicates that the first occurrence of x 1 becomes 0.
State compression Subset Issues