Блог пользователя CopyrightC

Автор CopyrightC, история, 4 месяца назад, По-английски

Hello everyone this is my first time posting, so please bare with me :P

So I was solving this problem and came up with a solution.

Idea

say for example x = 7. if ai is of the form 7d + 2 then aj needs to be of the form 7q + '5'. Basically the remainders of ai % x and aj % x needs to add up to x for the sum to be divisible by x. also for ai — aj to be divisible by y, ai % y must be same as aj % y.

Initialize a 2d vector(rems) with all values set to 0.

Loop through the input vector and calculate input%y(remy) and input%x(remx) increment rems[remy][remx].

calculate all possibilities by multiplying rems[remy][remx] * rems[remx][x-remx] at every iteration and add that to ans variable. also subtract the result of product of last time when we iterated through the same rems[remy][remx].

if say x = 8 and remx = 4; the we have to select combinations of 2 elements so we do Nc2 for such values.

    long long n,x,y;
    cin >> n >> x >> y;
    vector<vector<long long>> v(n);
    for(int i = 1;i < n; ++i) cin >> v[i];

    vector<vector<long long>> rems(y, vector<long long> (x, 0)); //init a 2d array
    ll ans = 0;
    ll remx,remy;
    ll curr,curr2;

    for(int i = 0; i < n;++i){
    	remy = v[i]%y;
    	remx = v[i]%x;
    	rems[remy][remx]++;
    	curr = rems[remy][remx];	
    	if(remx && remx!= (x- remx)){
    		curr2 = rems[remy][x-remx];
	    	ans += (curr * curr2) - ((curr - 1) * (curr2)); // on simplification = curr2
    	}
    	else{
    		ans+= (curr * (curr - 1))/2 - ((curr - 1) * (curr -2)/2); //Nc2 - (N-1)C2
    	}
    }

    cout << ans << '\n';	

I am unable to identify where am I going wrong? Exactly where is it taking so long? Specifically it gives TLE on test case 3. Also I don't wanna spoil the solution to me by reading tutorial.

If I'm unclear in any part of solution please do let me know. I'll try my best to explain again. Thanks!

Теги tle, c++, dp, o(n)
  • Проголосовать: нравится
  • +17
  • Проголосовать: не нравится

»
4 месяца назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Auto comment: topic has been updated by CopyrightC (previous revision, new revision, compare).

»
4 месяца назад, # |
  Проголосовать: нравится +8 Проголосовать: не нравится

You're getting TLE because you're initialising a $$$y$$$ by $$$x$$$ vector, where $$$x, y \le 10^9$$$.

  • »
    »
    4 месяца назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    For your use case, perhaps an std::map is more suitable?

    • »
      »
      »
      4 месяца назад, # ^ |
        Проголосовать: нравится +21 Проголосовать: не нравится

      I see. So basically under the hood it takes O(x*y) time to init every value to 0. Thanks a lot!