Dynamic Planning: add a set of "programming questions" and plan Addition
Programming question #1: Set Addition
Note: Total time limit: 3000 ms memory limit: 65536kB
Description
Returns two positive integers, A = {pi | 1 <= I <= a}, B = {qj | 1 <= j <= B}, and A positive integer s. The problem is: How many (I, j) pairs are different for pi + qj = s.
Input
The first row is the number of n groups of test data, followed by n groups of test data.
Each group of test data occupies 5 rows, with 1st rows being and s (1 <= s <= 10000), and 2nd rows being a positive integer a (1 <= a <= 10000 ), number of elements in. Row 3rd is a positive integer. Each positive integer cannot exceed 10000, indicating the elements in. Row 4th is a positive integer B (1 <= B <= 10000), indicating the number of elements in B. Row 5th is a positive integer of B. Each positive integer cannot exceed 10000, indicating the elements in B.
Note: The set here is slightly different from the set defined in the mathematical book-the set may contain an equal positive integer.
Output
N rows, each row of output corresponds to an input. The output should be a non-negative integer.
Sample Input
299249 49250 501191 2 3 4 5 6 7 8 91010 9 8 7 6 5 4 3 2 1
Sample output
49
Method 1:
This program uses the map container to collect statistics on repeated elements in the Set, and sorts the elements from small to large. Memory: 1664kB, time: 1476 ms
# Include
# Include
# Include using namespace std; int main () {int n, s, ni, nj; int a [10000], B [10000]; int nCount; map
Seti, setj; map
: Iterator nii, njj; cin> n; while (n --) {cin> s; cin> ni; for (int I = 0; I <ni; I ++) cin> a [I]; cin> nj; for (int j = 0; j <nj; j ++) cin> B [j]; sort (a, a + ni); // sort by elements from small to large sort (B, B + nj); int temp =-1; for (int I = 0; I <ni; I ++) {if (temp = a [I]) // collect statistics on repeated elements in the set. seti [a [I] ++; else seti [a [I] = 1; temp = a [I];} temp =-1; for (int j = 0; j <nj; j ++) {if (temp = B [j]) setj [B [j] ++; else setj [B [j] = 1; temp = B [j];} nCount = 0; for (nii = seti. begin (); nii! = Seti. end (); nii ++) {for (njj = setj. begin (); njj! = Setj. end (); njj ++) {if (nii-> first + njj-> first = s) nCount + = nii-> second * njj-> second ;}} cout <nCount <endl; seti. clear (); setj. clear () ;}return 0 ;}
Method 2:
Solve the problem by brute force. The memory size is 627 kb and the time is ms ......
#include
using namespace std;int sum, numA, numB;int arrayA[10001], arrayB[10001];int countHelper(int sum, int arrayA[], int numA, int arrayB[], int numB){ int count = 0; for (int i = 0; i < numA; ++i) { for (int j = 0; j < numB; ++j) { if (arrayA[i] + arrayB[j] == sum) { count++; } } } return count;}int main(){ int num; cin>>num; while(num--) { cin>> sum >> numA; for (int i = 0; i < numA; ++i) { cin>>arrayA[i]; } cin>>numB; for (int j = 0; j < numB; ++j) { cin>>arrayB[j]; } int count = countHelper(sum, arrayA, numA, arrayB, numB); cout<