[Problem] Write a C function which meets following conditions. (Development time: 4 hours) Write a C function which removes 999 cards according to the following rules, and returns the sum of numbers in cards which cannot be removed. If there are a number of ways to remove cards, you should choose the way which minimizes the return value. [Rules] If the sum of two cards of the same number is identical with the number in another card, you can remove these three cards. In other words, if there are cards as follows; 2 7 3 2 8 6 3 4 As 2+2=4, three cards of 2, 4, 2 can be removed. As 3+3=6, three cards of 3, 3, 6 also can be removed. Finally, two cards of 7, 8 remained. Therefore, return 15 (7+8 = 15). There is no fixed order to remove cards. In the example above, you can remove 2, 4, 2 first or remove 3, 3, 6 first. [Constraints] All cards have the numbers from 1 to 24, inclusive. DO NOT use any external libraries and the header file. [file 1 – ID number.cpp] // DD NOT INCLUDE ANY FILES int test_main(int data[999]) { return 0; //the sum of numbers in remaining cards after removing 3 cards each } [file 2 – main.cpp] #include <stdio.h> #include <stdlib.h> int test_main(int data[999]); void build_data(int data[999]) { for (int i = 0; i < 999; i ++) { data[i] = rand() % 24 + 1; } } void main(void) { int data[999]; for (int l = 0; l < 10; l++) { build_data(data); printf("%d\n", test_main(data)); } } #include <stdio.h> #include <stdlib.h> #include <cmath> int cmp(int a, int b) { return a<b; } void swap(int *a, int *b) { int tmp = *a; *a = *b; *b = tmp; } int test_main(int data[999]) { sort(data, data+999, cmp); /* for(int i=0; i<999; i++) { printf("%d ", data[i]); }*/ for(int i=997; i>0; i--) { if((-25!=data[i-1])&&(-25!=data[i]) && data[i-1] == data[i]) { for(int j=i+1; j<999; j++) { if((-25!=data[j])&& (data[i-1]+data[i])== data[j]) { data[i-1] = -25; data[i] = -25; data[j] = -25; } } } } //printf("\n"); int sum = 0; for(int i=0; i<999; i++) { // printf("%d ", data[i]); if(data[i]!=-25) sum+=data[i]; } // printf("\n"); return sum; } void build_data(int data[999]) { for (int i = 0; i < 999; i ++) { data[i] = rand() % 24 + 1; } } int main(void) { int data[999]; for (int l = 0; l < 1; l++) { build_data(data); // data[0]=2; data[1]=4;data[2]=7;data[3]=3;data[4]=3;data[5]=6; data[6]=2; // data[7]=8;data[8]=10; printf("%d\n", test_main(data)); } return 0; } |
|
来自: My_study_lib > 《笔试面试题目》