Now there are n items set V, each piece has a weight Wi, now from the inside to select a set S, so that the items in the V-S can be called out by the items in S, that is, in the left of a balance in the V-S of 1 item, then you must be able to select some items from S (can be used infinitely) on the Right, so that the balance of the balance.
The minimum number of elements in the Set S is required.
Now, we first find the Wi (I = 1, 2, 3... n), and then divide each Wi by g, so that gcd (Wi) = 1, this will not affect the final result. It is now proved that if the maximum public multiple of a subset of S in V is 1, all elements in V can be called out by elements in S.
It is proved that bé zout's identity theorem is used.
The current problem is to select the smallest set S from the set V, so that the public multiples of the Set S are the same as those of the set V (the same as 1 ).
Set DP [x] to the number of minimum sets with x as the maximum public multiple. Solve the problem through DP (actually BFS search). Then the final result is DP [1].
Int d [10000100];
Class BalanceScale
{
Public:
Int takeWeights (vector <int> w)
{
Int n = w. size ();
Int g = w [0]; for (int I = 1; I <n; I ++) g = gcd (g, w [I]);
For (int I = 0; I <n; I ++) w [I]/= g;
Sort (w. begin (), w. end ());
If (w [0] = 1) return 1;
Queue <int> q;
Memset (d, 1, sizeof (d ));
For (int I = 0; I <n; I ++) {q. push (w [I]); d [w [I] = 1 ;}
While (! Q. empty () & d [1] = 0x01010101)
{
Int u = q. front (); q. pop ();
For (int I = 0; I <n; I ++)
{
Int v = gcd (u, w [I]);
If (d [v] = 0x01010101) {d [v] = d [u] + 1; q. push (v );}
}
}
Return d [1];
}
};
The following is the DFS code: Import java. util .*;
Public class BalanceScale {
Int gcd (int x, int y ){
While (y! = 0 ){
Int t = x % y; x = y; y = t;
}
Return x;
}
Int [] w;
Int answer;
Void bt (int I, int d, int c ){
If (c> = answer ){
Return;
}
If (I = w. length ){
If (d = 1 ){
Answer = c;
}
Return;
}
Int d1 = gcd (d, w [I]);
If (d1! = D ){
Bt (I + 1, d1, c + 1 );
}
Bt (I + 1, d, c );
}
Public int takeWeights (int [] weight ){
Int d = 0;
For (int x: weight ){
D = gcd (d, x );
}
For (int I = 0; I <weight. length; I ++ ){
Weight [I]/= d;
}
W = weight;
Answer = weight. length;
Bt (0, 0, 0 );
Return answer;
}
}