Some wood sticks with the same length are cut into smaller ones and smaller ones, each with no more than 50 units in length. Now I want to make them look like they are, and I want to make them look like the shortest.
Idea: Deep Search + pruning
Pruning tips:
1. The length of the longest wooden stick must not exceed the length of the previous wooden stick.
2. If the total length cannot be exceeded
3. If the number of wooden sticks equals to the total length divided by the enumerated length of the wooden sticks, do not search down.
4. Add a wooden stick and mark it to avoid being searched again.
5. Sort from large to small, so if the current one cannot be added, it will be too large, as long as you search for smaller ones.
6. If you fail to return the result of a downward search, the length of the next block is the same as that of the current one. You do not need to search for the block and skip it directly.
# Include <iostream>
# Include <algorithm>
# Include <cstring>
Using namespace STD;
Int st [65];
Int mark [65];
Int S, J, N;
Bool CMP (int A, int B ){
Return A> B;
}
Bool DFS (INT sum, int K, int CNT) {// sum is the length of the wooden stick that is being spelled out. Where does K start with the broken wood block, CNT is the number of blocks in the fight
If (CNT = s) return true; // if the number of chunks is equal to the total length, divide it by the enumerated wooden stick Length
Else if (sum = J) return DFS (0, 0, CNT + 1); // if the root block is finished, splice the next one and start searching for the 0th sticks again
Else {
Int pre, I;
For (pre = 0, I = K; I <n; I ++) // enumerate wooden sticks
If (MARK [I] & St [I]! = Pre & St [I] + sum <= J) {// if this wooden stick has been attached and it is not equal to the length of the previous one
Pre = sT [I];
Mark [I] = false;
If (DFS (sum + st [I], I + 1, CNT) break; // search from the next wooden stick
Mark [I] = true; // If the downward search fails, the Backtracking is successful.
If (k = 0) return false; // if k = 0 after backtracing, it indicates that the restored wooden stick fails to be restored. That is to say, the remaining wooden sticks are insufficient to spell out the original wooden stick.
}
If (I = N) return false; else return true; // If I <n, it indicates that the result is searched. If I = N-1 is found, it indicates that the search fails, need to be rolled back
}
}
Int main (){
Int I, sum;
While (CIN> N, N ){
For (I = sum = 0; I <n; I ++ ){
Cin> st [I];
Sum + = sT [I];
}
Sort (St, ST + N, CMP );
For (j = sT [0]; j <sum; j ++) if (sum % J = 0) {// the maximum length of a wooden stick must not exceed the previous length.
S = sum/J;
Memset (mark, true, sizeof (Mark ));
If (DFS (0, 0, 0) break;
}
If (j = sum) cout <sum <Endl; else cout <j <Endl;
}
Return 0;
}