6991: Four-tuples
时间限制: 10 Sec 内存限制: 128 MB提交: 173 解决: 44
[ 提交][ 状态][ 讨论版][命题人: admin]
题目描述
输入
For each test case, the input contains one line with 8 integers l1,r1,l2, r2, l3,r3,l4,r4(1≤ li≤ ri≤ 10^9)
输出
样例输入
1
1 1 2 2 3 3 4 4
样例输出
1
题意,给出四个区间 l1,r1,l2,r2,l3,r3,l4,r4
求出(x1,x2,x3,x4)序列的个数,其中x1属于第一个序列,x2属于第二个序列..........
并且x1!=x2 x2!=x3 x3!=x4 x4!=x1
(x1可以等于x3,x2可以等于x4)
思路:
这是一题很明显的容斥原理题目。需要耐心推导公式。
首先将所有的情况(不考虑相等情况)的总集合设为A
那么
总集合A中包含满足 X1==X2 X1==X3 X1==X4 X2==X3 X2==X4 X3==X4 和 X1!=X2!=X3!=X4的所有序列
所以我们现在需要将只满足X1==X3 和 X2==X4 和X1!=X2!=X3!=X4 的所有序列留下,其余删去即可。
(只满足与满足不是同一概念)
满足X1==X2 的集合为a 满足X2==X3的集合为b 满足X3==X4的集合为c 满足X4==X1的集合为d
注:(1,1,2,2)和(1,1,1,2)这两个序列都属于集合a,应为两个序列都满足X1==X2
所以我们用
总集合 - a∪b∪c∪d == 所求序列集合
根据容斥定理
a∪b∪c∪d=|a|+|b|+|c|+|d| - |a∩b| - |b∩c| - |c∩a|- |a∩d| - |b∩d| - |c∩d|
+|a∩b∩c|+|a∩b∩d| +|a∩c∩d| +|b∩c∩d| -|a∩b∩c∩d|
其中 a∩b 为满足X1==X2==X3的序列集合
c∩a 为满足X1==X2 X3==X4 的序列集合
a∩b∩c和a∩b∩d和a∩b∩d和a∩b∩c∩d 都为满足X1==X2==X3==X4的集合
则:A-a∪b∪c∪d ==A-(|a|+|b|+|c|+|d| - |a∩b| - |b∩c| - |c∩a|- |a∩d| - |b∩d| -
|c∩d|+|a∩b∩c|+|a∩b∩d| +|a∩c∩d| +|b∩c∩d| -|a∩b∩c∩d|)
化简得: A-相邻两个相等的集合+相邻3个相等的集合+两对两个相等的 - 3*四个相等的
#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define M(a,b) memset(a,b,sizeof(a))
const LL MOD = 1e9+7;
struct Node///记录每个区间的左右端点和长度
{
LL l,r;
LL len;
} num[50];
LL ans;///记录最终答案
LL li,ri;
int main()
{
int T;
cin>>T;
while(T--)
{
M(num,0);
ans = 1;
for(int i=1; i<=4; i++)
{
scanf("%lld %lld",&li,&ri);
num[i] = Node{li,ri,ri-li+1};
num[i+4] = Node{li,ri,ri-li+1};///这步很重要,使得所有的相邻状态都可以被遍历到
ans = ans*num[i].len;///记录所有可能情况的种类
ans = (ans+MOD)%MOD;
}
for(int i=1; i<=4; i++)
{
LL lmax = max(num[i].l,num[i+1].l);
LL rmin = min(num[i].r,num[i+1].r);
LL tlen=0;
if(rmin-lmax+1>0) tlen = rmin-lmax+1;
ans-=tlen%MOD * num[i+2].len%MOD * num[i+3].len%MOD; ///减去相邻两个相等的状态
ans = (ans+MOD)%MOD;
}
for(int i=1; i<=4; i++)
{
LL lmax = max(num[i+2].l,max(num[i].l,num[i+1].l));
LL rmin = min(num[i+2].r,min(num[i].r,num[i+1].r));
LL tlen=0;
if(rmin-lmax+1>0) tlen = rmin-lmax+1;
ans+=tlen%MOD * num[i+3].len%MOD ;///加上相邻三个相等的状态
ans = (ans+MOD)%MOD;
}
for(int i=1; i<=2; i++)
{
LL lmax1 = max(num[i].l,num[i+1].l);
LL rmin1 = min(num[i].r,num[i+1].r);
LL lmax2 = max(num[i+3].l,num[i+2].l);
LL rmin2 = min(num[i+3].r,num[i+2].r);
LL tlen1=0;
LL tlen2=0;
if(rmin1-lmax1+1>0) tlen1 = rmin1-lmax1+1;
if(rmin2-lmax2+1>0) tlen2 = rmin2-lmax2+1;
ans+=tlen1%MOD * tlen2%MOD ;///加上两对两个相等的状态
ans = (ans+MOD)%MOD;
}
LL lmax = max(max(num[1].l,num[2].l),max(num[3].l,num[4].l));
LL rmin = min(min(num[1].r,num[2].r),min(num[3].r,num[4].r));
LL tlen=0;
if(rmin-lmax+1>0) tlen = rmin-lmax+1;
ans -=tlen %MOD * 3%MOD;///减去三个四个相等状态
ans = (ans+MOD)%MOD;
printf("%lld\n",ans);
}
return 0;
}