here is the c# text of the same idea:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
public static void ExaminePairOfRows(int i, int j)
{
long tempSum = 0;
// tempSum accepts all sums of intermediate buckets
tempSum = buckets[j-1,sqrtN-1]-buckets[i,sqrtN-1];
Stack<StackItem> leftStack = new Stack<StackItem>(sqrtN);
// construct left stack
for (int k = sqrtN - 1; k >= 0; --k)
{
long tempLeftSum = buckets[i, sqrtN - 1] - (k == 0 ? i==0 ? 0: buckets[i-1, sqrtN-1] : buckets[i, k - 1]);
while (leftStack.Count != 0 && leftStack.Peek().sum > tempLeftSum)
{
leftStack.Pop();
}
leftStack.Push(new StackItem(k+i*sqrtN, tempLeftSum));
}
Stack<StackItem> rightStack = new Stack<StackItem>(sqrtN);
// construct right stack
for (int k=0; k < sqrtN && buckets[j, k] < ((long)1 << 40); ++k)
{
long tempRightSum = buckets[j, k]-buckets[j-1,sqrtN-1];
while (rightStack.Count !=0 && rightStack.Peek().sum > tempRightSum )
{
rightStack.Pop();
}
rightStack.Push(new StackItem(k+j*sqrtN, tempRightSum));
}
Stack<StackItem> reversedRightStack = new Stack<StackItem>(sqrtN);
while (rightStack.Count != 0)
{
reversedRightStack.Push(rightStack.Pop());
}
while(leftStack.Count!=0) // greedy run over left and reversed-right stacks
{
StackItem tempLeftItem = leftStack.Pop();
StackItem tempReversedRightItem = new StackItem(-1,0);
while (reversedRightStack.Count!=0 && ( tempLeftItem.sum + tempSum + reversedRightStack.Peek().sum <=M ) )
{
tempReversedRightItem = reversedRightStack.Pop();
}
if(tempReversedRightItem.index!=-1)
{
int tempCount = tempReversedRightItem.index-tempLeftItem.index+1;
if ( maxProperties< tempCount)
{
maxProperties = tempCount;
firstIndex = tempLeftItem.index;
}
}
}
|
the program reads data from a text file which cosists of 2 rows : 1st row has 2 integers, 2nd row has 500,000 integers limited within -1,000,000 to +1,000,000.
Those 500,000 integers are stored in the buckets[708][707] array ( 500,000 items divided at sqrt(500,000) rows and columns, but not as they come from the text file - I stored them like a preffix array precalculated sums( array[j]-array[i] gives me the sum from i-th integer to j-th integer as they come from the text file ), idea is not sum numbers all the time, but to have sums as O(1).
up to this moment C# performs for about 50-60ms, C++ performs bit faster.
Then I use loop to call this function for each pair of buckets row i and j, where i<j,
to make my formal checks. There is one more method in the loop, which processes single row of the table, but it works fine - when I leave him alone ( the problematic one with stacks/vectors put in comments ) C++ behaves faster as expected.
I started to investigate my Visual Studio settings, is it possible to have some king of restriction there?