http://acm.hdu.edu.cn/showproblem.php?pid=4339
二分查找,这里的二分查找有点特别,因为low虽然在边,但是作为比较的左值是不变的。
View Code
1 #include <stdio.h> 2 #include <iostream> 3 #include <string.h> 4 using namespace std; 5 const int maxn = 1000005; 6 int ans[maxn]; 7 char str1[maxn],str2[maxn]; 8 int lowbit(int x) 9 { 10 return x & (-x); 11 } 12 int getSum(int x) 13 { 14 int i,sum=0; 15 for(i=x;i>0;i-=lowbit(i)) 16 sum+=ans[i]; 17 return sum; 18 } 19 void mod(int x,int c) 20 { 21 int i; 22 for(i=x;i<maxn;i+=lowbit(i)) 23 ans[i]+=c; 24 } 25 int min(int a,int b) 26 { 27 return a>b?b:a; 28 } 29 int fark(int low,int high) 30 { 31 int mid; 32 int ans; 33 ans=low; 34 while(low <= high) 35 { 36 mid=(low+high)/2; 37 if(getSum(mid+1)-getSum(ans+1)<mid-ans) 38 high=mid-1; 39 else 40 low=mid+1; 41 } 42 return low; 43 } 44 int main() 45 { 46 int t,n,i,j,a,b,d,f,len; 47 char s[10]; 48 scanf("%d",&t); 49 for(j=1;j<=t;j++) 50 { 51 printf("Case %d:\n",j); 52 memset(ans,0,sizeof(ans)); 53 scanf("%s%s",str1,str2); 54 len=min(strlen(str1),strlen(str2)); 55 for(i=0;i<len;i++) 56 { 57 if(str1[i]==str2[i]) 58 mod(i+1,1); 59 else 60 mod(i+1,0); 61 } 62 scanf("%d",&n); 63 while(n--) 64 { 65 scanf("%d",&d); 66 if(d%2) 67 { 68 scanf("%d%d%s",&a,&b,s); 69 if(str1[b]==str2[b]) 70 f=1; 71 else 72 f=0; 73 if(a%2) 74 str1[b]=s[0]; 75 else 76 str2[b]=s[0]; 77 if(f && str1[b]!=str2[b]) 78 mod(b+1,-1); 79 else if(!f && str1[b]==str2[b]) 80 mod(b+1,1); 81 } 82 else 83 { 84 scanf("%d",&a); 85 if(str1[a]!=str2[a]) 86 { 87 printf("0\n"); 88 continue; 89 } 90 b=fark(a,len-1); 91 printf("%d\n",getSum(b+1)-getSum(a+1)+1); 92 } 93 } 94 } 95 return 0; 96 }