题目描述
There are NN light bulbs indexed from 00 to N-1N−1. Initially, all of them are off.
A FLIP operation switches the state of a contiguous subset of bulbs. FLIP(L, R)FLIP(L,R) means to flip all bulbs xx such that L leq x leq RL≤x≤R. So for example, FLIP(3, 5)FLIP(3,5) means to flip bulbs 33 , 44 and 55, and FLIP(5, 5)FLIP(5,5) means to flip bulb 55.
Given the value of NN and a sequence of MM flips, count the number of light bulbs that will be on at the end state.
InputFile
The first line of the input gives the number of test cases, TT. TT test cases follow. Each test case starts with a line containing two integers NN and MM, the number of light bulbs and the number of operations, respectively. Then, there are MM more lines, the ii-th of which contains the two integers L_iLi and R_iRi, indicating that the ii-th operation would like to flip all the bulbs from L_iLi to R_iRi , inclusive.
1 leq T leq 10001≤T≤1000
1 leq N leq 10^61≤N≤106
1 leq M leq 10001≤M≤1000
0 leq L_i leq R_i leq N-10≤Li≤Ri≤N−1
OutputFile
For each test case, output one line containing Case #x: y, where xx is the test case number (starting from 11) and yy is the number of light bulbs that will be on at the end state, as described above.
样例输入
2 10 2 2 6 4 8 6 3 1 1 2 3 3 4
样例输出
Case #1: 4 Case #2: 3
代码
线段树会爆内存
直接搞差分法会t
想的是以类似于括号匹配的思路,每一个端点记录位置和左端点还是右端点。
因为“先操作2-6再操作4-8”与“先操作2-8再操作4-6”的结果是一样的,所以可以按照端点从小到大,左端点在右端点前的顺序排序。
排序后做一个栈并记录栈内元素,遍历排序后的数组,左端点入栈,遇右端点时,若当前栈内元素个数为奇数,ans加上这段的灯泡数;若当前为偶数,ans减去这段灯泡数(都要记得加一,这是个两头都种树的植树问题)。左端点退栈
其实思路我也没理太清楚反正过了……
先记下来再说()
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int maxn=1e6+5; 4 int table[maxn]; 5 struct node{ 6 int n; 7 int x;///1表示左端点,0表示右端点 8 }b[2005]; 9 bool cmp(struct node x,struct node y) 10 { 11 if (x.n==y.n) return x.x>y.x; 12 return x.n<y.n; 13 } 14 int s[2005]; 15 int main() 16 { 17 int t,n,m,l,r,cnt; 18 scanf("%d",&t); 19 for (int kase=1;kase<=t;kase++){ 20 memset(table,0,sizeof(table)); 21 //memset(b,0,sizeof(b)); 22 cnt=0; 23 struct node n1,n2; 24 scanf("%d %d",&n,&m); 25 for (int i=0;i<m;i++){ 26 scanf("%d %d",&l,&r); 27 n1.n=l; 28 n2.n=r; 29 n1.x=1;n2.x=0; 30 b[cnt]=n1; 31 b[cnt+1]=n2; 32 cnt+=2; 33 } 34 sort(b,b+cnt,cmp); 35 int ans=0;int k=0; 36 for (int i=0;i<cnt;i++){ 37 if (b[i].x==1){ 38 s[k]=b[i].n; 39 k++; 40 } 41 else{ 42 if (k%2!=0) ans+=b[i].n+1-s[k-1]; 43 else ans=-(b[i].n+1-s[k-1]-ans); 44 k--; 45 } 46 } 47 // long long tcnt=table[b[0]]; 48 // for (int i=1;i<cnt+1;i++){ 49 // if (tcnt%2!=0) ans+=b[i]-b[i-1]; 50 // tcnt+=table[b[i]]; 51 // } 52 printf("Case #%d: %d ",kase,ans); 53 } 54 return 0; 55 }
八百年了我终于把这题补上了(安详)