Ich brauche einen Weg, um das klassische 5SUM-Problem ohne Hashing oder mit einem speichereffizienten Weg des Hashing zu lösen.Lösung von 5SUM in O (n^3) mit strengen Speichergrenzen
Das Problem fragt, wie viele Teilfolgen in einer bestimmten Anordnung von Länge finden N die Summe gleich S haben
Ex:
Input
6 5
1 1 1 1 1 1
Output
6
Die Einschränkungen sind:
N <= 1000 (size of the array)
S <= 400000000 (the sum of the subsequence)
Memory usage <= 5555 kbs
Execution time 2.2s
Ich bin mir ziemlich sicher, dass die freigesetzte Komplexität O (N^3) ist. Aufgrund der Speicherbeschränkungen bietet das Hashing keine tatsächliche O (1) Zeit.
Das Beste, was ich bekam, war 70 Punkte mit diesem Code. (Ich habe TLE auf 6 Tests)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#define MAX 1003
#define MOD 10472
using namespace std;
ifstream in("take5.in");
ofstream out("take5.out");
vector<pair<int, int>> has[MOD];
int v[MAX];
int pnt;
vector<pair<int, int>>::iterator it;
inline void ins(int val) {
pnt = val%MOD;
it = lower_bound(has[pnt].begin(), has[pnt].end(), make_pair(val, -1));
if(it == has[pnt].end() || it->first != val) {
has[pnt].push_back({val, 1});
sort(has[pnt].begin(), has[pnt].end());
return;
}
it->second++;
}
inline int get(int val) {
pnt = val%MOD;
it = lower_bound(has[pnt].begin(), has[pnt].end(), make_pair(val, -1));
if(it == has[pnt].end() || it->first != val)
return 0;
return it->second;
}
int main() {
int n,S;
int ach = 0;
int am = 0;
int rez = 0;
in >> n >> S;
for(int i = 1; i <= n; i++)
in >> v[i];
sort(v+1, v+n+1);
for(int i = n; i >= 1; i--) {
if(v[i] > S)
continue;
for(int j = i+1; j <= n; j++) {
if(v[i]+v[j] > S)
break;
ins(v[i]+v[j]);
}
int I = i-1;
if(S-v[I] < 0)
continue;
for(int j = 1; j <= I-1; j++) {
if(S-v[I]-v[j] < 0)
break;
for(int k = 1; k <= j-1; k++) {
if(S-v[I]-v[j]-v[k] < 0)
break;
ach = S-v[I]-v[j]-v[k];
rez += get(ach);
}
}
}
out << rez << '\n';
return 0;
}
Was 'N' in Zwänge ist? Größe des Arrays? – vish4071
Ja, ich habe vergessen, das zu erwähnen. – RazvanD
und was ist die Einschränkung für 'S'? Summe? Warum benutzt du auch 'mod'? – vish4071