XOR——思维

题目描述 
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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值