UVA 10125 - Sumsets
链结:戳我。
AC了。这道题我参考了这里:狠狠地戳我。我觉得他的解释非常的棒:
找到a + b的和的所有情况。
然后看d - c在不在里面。
最后算法是O(n^2log(n))
View Code
1 /* 2 Author: frankdj 3 State: AC 4 */ 5 #include <iostream> 6 #include <cstring> 7 #include <algorithm> 8 using namespace std; 9 10 struct Node{ 11 long long value; 12 int x; 13 int y; 14 }; 15 16 const int kMaxNumEle = 1001; 17 const int kMaxHashSize = 100000; 18 19 Node sum[kMaxNumEle*kMaxNumEle]; 20 int elements[kMaxNumEle], num_element, num_sum; 21 int head[kMaxHashSize], next[kMaxNumEle*kMaxNumEle]; 22 23 void InitLookupTable() { 24 memset(head, 0, sizeof(head)); 25 memset(next, 0, sizeof(next)); 26 } 27 28 int Hash(long long key) { 29 return (int)((key & 0x7fffffff) % kMaxHashSize); 30 } 31 32 void Insert(int index) { 33 int hash = Hash(sum[index].value); 34 next[index] = head[hash]; 35 head[hash] = index; 36 } 37 38 bool IsDifferent(int i, int j, int index) { 39 int x = sum[index].x; 40 int y = sum[index].y; 41 if (i == x || i == y || j == x || j == y) 42 return false; 43 else 44 return true; 45 } 46 47 bool Find(long long number, int i, int j) { 48 int hash = Hash(number); 49 int index = head[hash]; 50 while (index != 0) { 51 if (sum[index].value == number) 52 if (IsDifferent(i, j, index)) 53 return i; 54 else 55 index = next[index]; 56 else 57 index = next[index]; 58 } 59 return false; 60 } 61 62 int Search() { 63 for (int i = num_element; i >= 1; i--){ 64 for (int j = 1; j != i && j <= num_element; j++){ 65 if (Find(elements[i] - elements[j], i, j)) 66 return i; 67 } 68 } 69 return 0; 70 } 71 72 73 int main(int argc, char *argv[]){ 74 #ifndef ONLINE_JUDGE 75 freopen("input.txt", "r", stdin); 76 #endif 77 78 while (cin >> num_element && num_element != 0) { 79 memset(sum, 0, sizeof(sum)); 80 memset(elements, 0, sizeof(elements)); 81 82 for (int i = 1; i <= num_element; i++) 83 cin >> elements[i]; 84 85 sort(elements+1, elements+num_element+1); 86 87 num_sum = 1; 88 for (int i = 1; i <= num_element; i++){ 89 for (int j = i+1; j <= num_element; j++){ 90 sum[num_sum].value = elements[i] + elements[j]; 91 sum[num_sum].x = i; 92 sum[num_sum].y = j; 93 Insert(num_sum); 94 num_sum++; 95 } 96 } 97 num_sum--; 98 99 int ans = Search(); 100 if (ans != 0) { 101 cout << elements[ans] << endl; 102 } 103 else { 104 cout << "no solution" << endl; 105 } 106 } 107 return 0; 108 }
这里的东西都是自娱自乐的.我只是抱着构思算法的心态去做UVA的题.
我所有的code都不可能AC的.因为我就没想着让它能AC.