题目描述
Once there was a king called XOR, he had a lot of land. Because of his name, he likes to play XOR games.
One day, he whimpered and wanted to establish N cities on that vast expanse of land, numbered 0, 1, 2..., N-1. He wanted to connect all the cities. If city A can reach City B through zero or one or several cities, then A and B are connected. The cost of repairing a road in City A and City B is the XOR value of number of City A and number of City B. This King XOR wanted to figure out the minimum cost for connecting all of the N cities.
Of course, like a fairy tale read as a child, there will be corresponding rewards after helping the king. If you help the king solve his problems, he will improve your ranking in the competition.
输入描述:
There are multi test cases
each test cases contains an integer N (2 ≤N≤ 20000), the number of cities the king wants to establish.
输出描述:
For each test case, print the minimum cost for connecting all of the N cities in one line.
示例1
输入
4
输出
4
说明
Once there was a king called XOR, he had a lot of land. Because of his name, he likes to play XOR games.
One day, he whimpered and wanted to establish N cities on that vast expanse of land, numbered 0, 1, 2..., N-1. He wanted to connect all the cities. If city A can reach City B through zero or one or several cities, then A and B are connected. The cost of repairing a road in City A and City B is the XOR value of number of City A and number of City B. This King XOR wanted to figure out the minimum cost for connecting all of the N cities.
Of course, like a fairy tale read as a child, there will be corresponding rewards after helping the king. If you help the king solve his problems, he will improve your ranking in the competition.
输入描述:
There are multi test cases
each test cases contains an integer N (2 ≤N≤ 20000), the number of cities the king wants to establish.
输出描述:
For each test case, print the minimum cost for connecting all of the N cities in one line.
示例1
输入
4
输出
4
说明
The weightof the minimum cost is 1+2+1=4 In the Sample Example.
思路:找一个最小生成树,节点0~n-1之间距离的权值是抑或和~
由此我们不难猜出,想要异或和最小,那么最好是差的不一样的位数是1个位最好,通过枚举找规律可知,每个距离的权值是最低位1决定的。例:
如样例 n=4 那就是0-3之间连接;
0=0000
1=0001 ->最低位1在0 所以和0连接 总值+1(2^0)
2=0010 ->最低位1在1 所以和0连接 总值+2(2^1)
3=0011 ->最低位1在1 所以和2连接 总值+1(2^1)
最后答案为4;
那么简单方法就是直接用lowbit函数(最低位1的和):
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
long long sum=0;
for(int i=0;i<n;i++)
{
sum+=i&(-i);
}
cout<<sum<<endl;
}
}
488

被折叠的 条评论
为什么被折叠?



