在计数时,必须注意没有重复,没有遗漏。为了使重叠部分不被重复计算,人们研究出一种新的计数方法,这种方法的基本思想是:先不考虑重叠的情况,把包含于某内容中的所有对象的数目先计算出来,然后再把计数时重复计算的数目排斥出去,使得计算的结果既无遗漏又无重复,这种计数的方法称为容斥原理
要计算几个集合并集的大小,我们要先将所有单个集合的大小计算出来,然后减去所有两个集合相交的部分,再加回所有三个集合相交的部分,再减去所有四个集合相交的部分,依此类推,一直计算到所有集合相交的部分。
E. Four-tuples [ 问题 2823 ] [ 讨论 ]
Description
Given l1,r1,l2,r2,l3,r3,l4,r4, please count the number of four-tuples (x1,x2,x3,x4) such that li≤xi≤ri and x1≠x2,x2≠x3,x3≠x4,x4≠x1. The answer should modulo 109+7 before output.
Input
The input consists of several test cases. The first line gives the number of test cases, T(1≤T≤106).
For each test case, the input contains one line with 8 integers l1,r1,l2,r2,l3,r3,l4,r4(1≤li≤ri≤109)
Output
For each test case, output one line containing one integer, representing the answer.
Samples
Input 复制
1
1 1 2 2 3 3 4 4
Output
1
Source
第九届山东省赛
#include<bits/stdc++.h>
#include<stdio.h>
#include<string.h>
using namespace std;
#define PI 3.1415926535897932384626433832795028841971693993751058209749445923078164062
typedef long long ll;
typedef pair<int,int> PII;
ll mod=1e9+7;
int qow_m(int n,int w){int k=1;while(w){if(w&1)k=k*n%mod; n=n*n%mod; w>>=1;}return k%mod; }
const int maxn =1e7+7 ;//..ll sum=1;
ll lowbit(ll x) {return x&(-x);}
ll n,m,k,wz,cnt=0,h,num=0;
ll x,y=0;
int a[100005];
ll j2(ll x1,ll y1,ll x2,ll y2){
ll dx=max(x1,x2);
ll dy=min(y1,y2);
if(dy>=dx)
return dy-dx+1;
return 0;
}
ll j3(ll x1,ll y1,ll x2,ll y2,ll x3,ll y3){
ll dx=max(x1,max(x2,x3));
ll dy=min(y1,min(y2,y3));
if(dy>=dx)
return dy-dx+1;
return 0;
}
ll j4(ll x1,ll y1,ll x2,ll y2,ll x3,ll y3,ll x4,ll y4){
ll dx=max(max(x1,x2),max(x3,x4));
ll dy=min(min(y1,y2),min(y4,y3));
if(dy>=dx){
return dy-dx+1;
}
return 0;
}
int main(){
ll l1,r1,l2,r2,l3,r3,l4,r4;
int T;
scanf("%d",&T);
while(T--){
scanf("%lld %lld %lld %lld %lld %lld %lld %lld",&l1,&r1,&l2,&r2,&l3,&r3,&l4,&r4);
ll sum=1;
sum=(sum*(r1-l1+1))%mod;
sum=(sum*(r2-l2+1))%mod;
sum=(sum*(r3-l3+1))%mod;
sum=(sum*(r4-l4+1))%mod;
sum=((sum-(j2(l1,r1,l2,r2)*((r3-l3+1)*(r4-l4+1)%mod)%mod)%mod)+mod)%mod;// 1 2
// cout<<sum<<endl;
sum=((sum-(j2(l3,r3,l2,r2)*(((r1-l1+1)%mod)*((r4-l4+1)%mod)%mod)%mod)%mod)+mod)%mod; // 2 3
sum=((sum-(j2(l3,r3,l4,r4)*(((r1-l1+1)%mod)*((r2-l2+1)%mod)%mod)%mod)%mod)+mod)%mod;// 3 4
sum=((sum-(j2(l1,r1,l4,r4)*(((r3-l3+1)%mod)*((r2-l2+1)%mod)%mod)%mod)%mod)+mod)%mod;// 1 4
//cout<<sum<<endl;
sum=(sum+(j3(l1,r1,l2,r2,l3,r3)*(r4-l4+1)%mod)%mod)%mod;// 1 2 3
sum=(sum+(j3(l1,r1,l2,r2,l4,r4)*(r3-l3+1)%mod)%mod)%mod;//1 2 4
// cout<<j3(l1,r1,l2,r2,l3,r3)<<endl;
//cout<<sum<<endl;
sum=(sum+(j3(l1,r1,l4,r4,l3,r3)*(r2-l2+1)%mod)%mod)%mod;// 1 3 4
sum=(sum+(j3(l4,r4,l2,r2,l3,r3)*(r1-l1+1)%mod)%mod)%mod; // 2 3 4
//cout<<sum<<endl;
sum=(sum+j2(l1,r1,l2,r2)*j2(l3,r3,l4,r4)%mod)%mod;// 1==2 && 3==4
sum=(sum+j2(l3,r3,l2,r2)*j2(l1,r1,l4,r4)%mod)%mod; // 2 3 1 4
// cout<<sum<<endl;
sum=((sum-(3*j4(l1,r1,l2,r2,l3,r3,l4,r4)%mod)%mod)+mod)%mod;
printf("%lld\n",sum);
}
return 0;
}