[国家集训队]小Z的袜子

嘟嘟嘟


一眼就知道是莫队。


还不带修改,美滋滋。
按莫队的方法排序,然后用小学数学算一下概率,分子分母单独维护。

#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
#define enter puts("") 
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define rg register
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
const int maxn = 5e4 + 5;
inline ll read()
{
  ll ans = 0;
  char ch = getchar(), last = ' ';
  while(!isdigit(ch)) last = ch, ch = getchar();
  while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
  if(last == '-') ans = -ans;
  return ans;
}
inline void write(ll x)
{
  if(x < 0) x = -x, putchar('-');
  if(x >= 10) write(x / 10);
  putchar(x % 10 + '0');
}

int n, m, S, a[maxn];
int cnt = 0, tot[maxn];
#define bel(x) (((x) - 1) / S + 1)
struct Node
{
  int L, R, id;
  bool operator < (const Node& oth)const
  {
    return bel(L) < bel(oth.L) || (bel(L) == bel(oth.L) && R < oth.R);
  }
}q[maxn];
struct Ans
{
  ll x, y;
}ans[maxn];

inline ll gcd(ll a, ll b) {return b ? gcd(b, a % b) : a;}

inline void add(int x)
{
  cnt += (tot[x] << 1);
  tot[x]++;
}
inline void del(int x)
{
  cnt -= ((tot[x] - 1) << 1);
  tot[x]--;
}

int main()
{
  n = read(); m = read(); S = sqrt(n);
  for(int i = 1; i <= n; ++i) a[i] = read();
  for(int i = 1; i <= m; ++i) q[i].L = read(), q[i].R = read(), q[i].id = i;
  sort(q + 1, q + m + 1);
  int l = 1, r = 0;
  for(int i = 1; i <= m; ++i)
    {
      while(l < q[i].L) del(a[l++]);
      while(l > q[i].L) add(a[--l]);
      while(r < q[i].R) add(a[++r]);
      while(r > q[i].R) del(a[r--]);
      if(!cnt) ans[q[i].id] = (Ans){0, 1};
      else
	{
	  ll len = q[i].R - q[i].L + 1, d = gcd(cnt, (ll)len * (ll)(len - 1));
	  ans[q[i].id] = (Ans){cnt / d, (ll)len * (len - 1) / d};
	}
    }
  for(int i = 1; i <= m; ++i) write(ans[i].x), putchar('/'), write(ans[i].y), enter;
  return 0;
}
原文地址:https://www.cnblogs.com/mrclr/p/10077550.html