SOJ - 11598
2014-10-21 22:43
295 查看
11598. XOR
Constraints
Time Limit: 1 secs, Memory Limit: 256 MBDescription
Given two integers S and F, what is the XOR (exclusive-or) of all numbers between S andF (inclusive)?Input
The first line of input is the integer T, which is the number of test cases (1 ≤ T ≤ 1000). Tlines follow, with each line containing two integers S and F (1 ≤ S ≤ F ≤ 1 000 000 000).Output
For each test case, output the (decimal) value of the XOR of all numbers between S and F, inclusive.Sample Input
5 3 10 5 5 13 42 666 1337 1234567 89101112
Sample Output
8 5 39 0 89998783
Problem Source
2014年每周一赛第八场题意:计算区间[S,F]所有整数的异或和。
思路:先讨论S==1时的情况:若F为奇数,则看F/2是否为奇数,若是则结果为0,否则为1;若F为偶数,则看F/2是否为奇数,若是则结果为F+1,否则为F。
S^...^F == (1^...^F) ^ (1^...^(S - 1))
// Problem#: 11598 // Submission#: 3058633 // The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License // URI: http://creativecommons.org/licenses/by-nc-sa/3.0/ // All Copyright reserved by Informatic Lab of Sun Yat-sen University #include<bits/stdc++.h> using namespace std; int main() { int t,s,f,ss,ff; scanf("%d",&t); while(t--) { scanf("%d%d",&s,&f); if(f&1)ff=!((f>>1)&1);else ff=f+((f>>1)&1); s--; if(s&1)ss=!((s>>1)&1);else ss=s+((s>>1)&1); printf("%d\n",ff^ss); } return 0; }
今天又研究出另一种解法:
先来观察一组二元序列:
00,01,10,11;
100,101,110,111;
1000,1001,1010,1011;
……
可见每组元素的异或和一定为0,即只要F的二进制表示以11结尾,那么区间[0,F]内所有整数的异或和一定为0.
于是有下面这个公式:
设sumofxor(x)为区间[0,x]内所有整数的异或和,则有
// Problem#: 11598 // Submission#: 3063400 // The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License // URI: http://creativecommons.org/licenses/by-nc-sa/3.0/ // All Copyright reserved by Informatic Lab of Sun Yat-sen University #include<bits/stdc++.h> using namespace std; int sumofxor(int x) { int i,j,s; for(i=0;i<=3;i++) if((x & 0x3) == i) { s = 0; for(j=3-i;j>=1;j--)s ^= (x + j); return s; } return 0; } int main() { int t,s,f; scanf("%d",&t); while(t--) { scanf("%d%d",&s,&f); printf("%d\n",sumofxor(f) ^ sumofxor(s-1)); } return 0; }
相关文章推荐
- soj 11598. XOR
- 2^n的第一位数字 soj 3848 mathprac
- soj 3252 大组合数取模
- SOJ 3137: Simple Computing _容斥原理
- SOJ 4164 贪心
- SOJ 3134: windy和水星 -- 水星交通
- soj 1498. Elementary Additions
- soj 1363. Semi-prime H-numbers
- soj - 1815 - 计算两点间的距离
- soj 1488. 矩阵取数游戏
- SOJ 8058 Matrix
- Sicily 1252 Defining Moment (SOJ 1252) 【暴力匹配】
- soj1049.Mondriaan
- soj 9161. VOYAGER
- soj 1698 Hungry Cow_三角函数
- SOJ 1176. Two Ends
- SOJ 12259 Message Relay (dfs,图联通)
- SOJ 3191 Free square
- soj 4243 最短路 spfa实现
- SOJ.AutoReset