bzoj 3198: [Sdoi2013]spring hash+容斥原理

题意

给定n个元素,每个元素是一个六元组,求有多少对元素满足相同的位置恰好有k个。
n<=100000

分析

很容易想到容斥原理。
不难发现,容斥系数要乘上一个组合数 Cky ,y表示选了多少个位置。证明的话,感受一下就好了。

代码

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;

typedef long long LL;

const int N=100005;
const int mo1=1000007;
const int mo2=998244353;
const int ba1=233;
const int ba2=1221;

int n,m,a[N][7],cnt,q[N],last[mo1];
LL ans;
bool vis[7];
struct edge{int next,w2,s;}e[N];

int read()
{
    int x=0,f=1;char ch=getchar();
    while (ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while (ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}

int C(int x,int y)
{
    int ans=1;
    for (int i=y+1;i<=x;i++) ans*=i;
    for (int i=1;i<=x-y;i++) ans/=i;
    return ans;
}

int ins(int w1,int w2)
{
    for (int i=last[w1];i;i=e[i].next)
        if (e[i].w2==w2)
        {
            e[i].s++;
            return e[i].s-1;
        }
    e[++cnt].w2=w2;e[cnt].s=1;e[cnt].next=last[w1];last[w1]=cnt;
    return 0;
}

void calc(int y)
{
    LL tot=0;int top=0;cnt=0;
    for (int i=1;i<=n;i++)
    {
        int w1=0,w2=0;
        for (int j=1;j<=6;j++)
            if (vis[j])
            {
                w1=((LL)w1*ba1+(LL)a[i][j])%mo1;
                w2=((LL)w2*ba2+(LL)a[i][j])%mo2;
            }
        tot+=ins(w1,w2);q[++top]=w1;
    }
    while (top) last[q[top]]=0,top--;
    if ((y-m)%2==0) ans+=(LL)tot*C(y,m);
    else ans-=(LL)tot*C(y,m);
}

void dfs(int x,int y)
{
    if (x>6)
    {
        if (y>=m) calc(y);
        return;
    }
    dfs(x+1,y);
    vis[x]=1;
    dfs(x+1,y+1);
    vis[x]=0;
}

int main()
{
    n=read();m=read();
    for (int i=1;i<=n;i++)
        for (int j=1;j<=6;j++)
            a[i][j]=read();
    dfs(1,0);
    printf("%lld",ans);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值