• + 0 comments

    Same idea as Daniel_v_oconnor, but the code is a little easier to understand.

      
    	
    long gcd(long a, long b)
    {
      if (b == 0) return a;
      return gcd(b, a % b);
    }
    
    string solve(long n, int k, string s)
    {
      int a=0,b;
      long cnt=0,sum=0;
      for (b = 0; b <= k; b++) 
        if (s[b]=='1') sum++;
      for(a=0,b=k+1;a<n;a++,b++) {
        if (s[a]=='1') cnt+=sum;
        if (a>=k) sum-=s[a-k]=='1';
        if (b<n) sum+=s[b]=='1';
      }
      long nxn = n * n, div = gcd(cnt, nxn);
      cnt /= div, nxn /= div;
      return to_string(cnt) + "/" + to_string(nxn);
    }