There are n soldiers and m weapons. Each weapon has a certain weight, and each soldier has a range of weapons, including minw and maxw, find out how many soldiers can get their weapons at most.
Train of Thought: this was the first game we held with the training team of the armed forces yesterday afternoon. When I first saw this question, I thought of greed. I submitted wa once, and then began to think about other ideas. Later I thought about binary matching, however, because there are too many edges (n is 2500, m is 40000), as expected, tle has been suffering from the tragedy until the end. There are two major questions ,,,,,
Correct Thinking: greedy. Sort by the Left endpoint of each interval, and then use the loop. It should be noted that when the cycle is running, you need to consider a situation where one interval contains another. In this case, you need to take special measures. It can be processed in advance during sorting. This is not the case when the loop is reversed.
Code:
[Cpp] www.2cto.com
# Include <iostream>
# Include <cstdio>
# Include <string. h>
# Include <algorithm>
Using namespace std;
# Define CLR (arr, val) memset (arr, val, sizeof (arr ))
Const int N = 3000, M = 41000;
Struct sold {
Int maxw, minw;
} Ss [N];
Bool cmp (sold a, sold B ){
If (a. minw = B. minw)
Return a. maxw <B. maxw;
Else if (a. minw> B. minw & a. maxw <= B. maxw)
Return true;
Else if (a. minw <= B. minw & a. maxw> = B. maxw)
Return false;
Return a. minw <B. minw;
}
Int main (){
// Freopen ("1.txt"," r ", stdin );
Int n, m;
While (scanf ("% d", & n, & m )! = EOF ){
For (int I = 0; I <n; ++ I)
Scanf ("% d", & ss [I]. minw, & ss [I]. maxw );
Int weight [M];
For (int I = 0; I <m; ++ I)
Scanf ("% d", & weight [I]);
Sort (ss, ss + n, cmp );
Sort (weight, weight + m );
Int sum = 0, flag [M], pos = 0;
CLR (flag, 0 );
For (int I = 0; I <n; ++ I ){
For (int j = 0; j <m; ++ j ){
If (ss [I]. minw <= weight [j] & weight [j] <= ss [I]. maxw &&! Flag [j]) {
Sum ++;
Flag [j] = 1;
Pos = j + 1;
Break;
}
}
}
Printf ("% d \ n", sum );
}
Return 0;
}
Author: wmn_wmn