update
This commit is contained in:
parent
1f1ad49427
commit
6f050a029e
2496 changed files with 37609 additions and 3031 deletions
|
|
@ -0,0 +1,30 @@
|
|||
import std.stdio;
|
||||
|
||||
inout(T[]) maxSubseq(T)(inout T[] sequence) pure nothrow {
|
||||
int maxSum, thisSum, i, start, end = -1;
|
||||
|
||||
foreach (j, x; sequence) {
|
||||
thisSum += x;
|
||||
if (thisSum < 0) {
|
||||
i = j + 1;
|
||||
thisSum = 0;
|
||||
} else if (thisSum > maxSum) {
|
||||
maxSum = thisSum;
|
||||
start = i;
|
||||
end = j;
|
||||
}
|
||||
}
|
||||
|
||||
if (start <= end && start >= 0 && end >= 0)
|
||||
return sequence[start .. end + 1];
|
||||
else
|
||||
return [];
|
||||
}
|
||||
|
||||
void main() {
|
||||
const a1 = [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1];
|
||||
writeln("Maximal subsequence: ", maxSubseq(a1));
|
||||
|
||||
const a2 = [-1, -2, -3, -5, -6, -2, -1, -4, -4, -2, -1];
|
||||
writeln("Maximal subsequence: ", maxSubseq(a2));
|
||||
}
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
import std.stdio, std.algorithm, std.range, std.typecons;
|
||||
|
||||
mixin template InitsTails(T) {
|
||||
T[] data;
|
||||
size_t pos;
|
||||
@property bool empty() { return pos > data.length; }
|
||||
void popFront() { pos++; }
|
||||
}
|
||||
|
||||
struct Inits(T) {
|
||||
mixin InitsTails!T;
|
||||
@property T[] front() { return data[0 .. pos]; }
|
||||
}
|
||||
|
||||
auto inits(T)(T[] seq) { return seq.Inits!T; }
|
||||
|
||||
struct Tails(T) {
|
||||
mixin InitsTails!T;
|
||||
@property T[] front() { return data[pos .. $]; }
|
||||
}
|
||||
|
||||
auto tails(T)(T[] seq) { return seq.Tails!T; }
|
||||
|
||||
auto maxSubseq(T)(T[] seq) /*pure nothrow*/ {
|
||||
//return seq.tails.map!inits.join.reduce!(max!q{ a.sum });
|
||||
return seq
|
||||
.tails
|
||||
.map!inits
|
||||
.join
|
||||
.map!q{ tuple(reduce!q{a + b}(0, a), a) }
|
||||
.reduce!max[1];
|
||||
}
|
||||
|
||||
void main() {
|
||||
[-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1].maxSubseq.writeln;
|
||||
[-1, -2, -3, -5, -6, -2, -1, -4, -4, -2, -1].maxSubseq.writeln;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue