2

Here is the question Spoj-WEIRDFN

Problem:

Let us define :

F[1] = 1
F[i] = (a*M[i] + b*i + c)%1000000007 for i > 1

where M[i] is the median of the array {F[1],F[2],..,F[i-1]} Given a,b,c and n, calculate the sum F[1] + F[2] + .. + F[n].

Constraints:

0 <= a,b,c < 1000000007
1 <= n <= 200000

I came up with a solution which is not so efficient

MY SOLUTION::--

#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define mod 1000000007
int main() {
    // your code goes here
    int t;
    scanf("%d",&t);
    while(t--)
    {
      ll a,b,c,sum=0;
      int n;
      scanf("%lld%lld%lld%d",&a,&b,&c,&n);
      ll f[n+1];
      f[1]=1;
      f[0]=0;
      for(int i=2;i<=n;i++)
      {  
          ll temp;
          sort(&f[1],&f[i]);
          temp=f[i/2];
          f[i]=((a*(temp)%mod)+((b*i)%mod)+(c%mod))%mod;
          sum+=f[i];
      }
      printf("%lld\n",sum+f[1]);
    }
    return 0;
}

Can anybody give me hint for for better algorithm or data structure for this task

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

1 Answers1

1

For each test case, you can maintain a binary search tree, thus you can find the median of n elements in O(log n) time, and you only need O(log n) time to add a new element into the tree.

Thus, we have an O(T*nlogn) algorithm, with T is number of test case, and n is number of elements, which should be enough to pass.

Community
  • 1
  • 1
Pham Trung
  • 11,204
  • 2
  • 24
  • 43
  • I once thought of implementing this using stl(priority_queue)..but than i thought i will still lead me to TLE..BST is the best i can do.Thanks for suggestion – doodle doodle Mar 03 '15 at 07:22
  • It's important to keep the BST *balanced*, so that you only need to consider the root and possibly its children to find the median. Otherwise (e.g. if all inputs are in increasing order) your BST could wind up looking like a linked list, and the per-test-case running time will balloon out to O(n^2). – j_random_hacker Mar 03 '15 at 12:48