Codeforces Round #647 (Div. 2) - Thanks, Algo Muse! C. Johnny and Another Rating Drop
The last contest held on Johnny's favorite competitive programming platform has been received rather positively. However, Johnny's rating has dropped again! He thinks that the presented tasks are lovely, but don't show the truth about competitors' skills.
The boy is now looking at the ratings of consecutive participants written in a binary system. He thinks that the more such ratings differ, the more unfair is that such people are next to each other. He defines the difference between two numbers as the number of bit positions, where one number has zero, and another has one (we suppose that numbers are padded with leading zeros to the same length). For example, the difference of 5=10125=1012 and 14=1110214=11102 equals to 33, since 01010101 and 11101110 differ in 33 positions. Johnny defines the unfairness of the contest as the sum of such differences counted for neighboring participants.
Johnny has just sent you the rating sequence and wants you to find the unfairness of the competition. You have noticed that you've got a sequence of consecutive integers from 00 to nn. That's strange, but the boy stubbornly says that everything is right. So help him and find the desired unfairness for received numbers.
The input consists of multiple test cases. The first line contains one integer tt (1≤t≤100001≤t≤10000) — the number of test cases. The following tt lines contain a description of test cases.
The first and only line in each test case contains a single integer nn (1≤n≤1018)1≤n≤1018).
Output tt lines. For each test case, you should output a single line with one integer — the unfairness of the contest if the rating sequence equals to 00, 11, ..., n−1n−1, nn.
5 5 7 11 1 2000000000000
8 11 19 1 3999999999987
For n=5n=5 we calculate unfairness of the following sequence (numbers from 00 to 55 written in binary with extra leading zeroes, so they all have the same length):
- 000000
- 001001
- 010010
- 011011
- 100100
- 101101
The differences are equal to 11, 22, 11, 33, 11 respectively, so unfairness is equal to 1+2+1+3+1=81+2+1+3+1=8.
最初用了个循环发现例子的数太大会超时,用循环的方法看数据我又发现按照n下去好像有某种规律1213121412131215......但还是我太天真了。。
二进制其实是逢2进1,如果我们按照每一位来逐一照看,最开始的第一位101010变化所以所以ans=ans+n,第二位在第一位的基础之上00110011变换ans=ans+n/2,以此类推得出答案
1 #include<iostream> 2 using namespace std; 3 int main() 4 { 5 int t; 6 cin>>t; 7 for(int lizi=0;lizi<t;lizi++) 8 { 9 long long n,i=1,j=1,ans=0; 10 cin>>n; 11 while(j<(n<<1)) 12 { 13 ans=ans+n/i; 14 i=i*2; 15 j=j<<1; 16 } 17 cout<<ans<<endl; 18 } 19 }

浙公网安备 33010602011771号