zoukankan      html  css  js  c++  java
  • 新疆大学ACM-ICPC程序设计竞赛五月月赛(同步赛)- XOR(二进制使用)

    链接:https://www.nowcoder.com/acm/contest/116/H
    来源:牛客网

    题目描述

    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.

    题意:输入一个数N让你从0-N之间做一个最小生成树(连接两个数之间的消耗就是两个数异或的值)


    思路:
    首先我们先了解一下异或,就是把数字换算成二进制 两个数异或比较如果同位上 相同为0 不同为1
    例如 3异或4 就是(假设四位二进制)
       3:0011
       4:0100
      3^4:0111
    那么3^4=0111->换算成十进制就是7

    那么回到题意,如果一个数想要加入到最小生成树中那么就要异或一个值使得异或的值最小;
    异或最小的话那就是只有最低位不相同其他位全部相同;
    所以每次只要找出当前数的最低位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;


    代码:
    #include<bits/stdc++.h>
    using namespace std;
    #define ll long long
    int main()
    {
            int n,m;
            while(cin>>n){
                    int num=0;
                    for(int i=1;i<n;i++){
                            int ans=i;
                            int cnt=0;
                            while((ans&1)==0){//一定要有括号
                                    ans>>=1;
                                    cnt++;
                            }
                            num+=pow(2,cnt);
    
                    }
                    cout<<num<<endl;
            }
            return 0;
    }
    
    
    

      

     
  • 相关阅读:
    一个省一等奖没文件没证书,只能保存一张图呢
    HTML5的新结构标签
    一个最简单的网页是如何构成的
    数据模型层Model
    空控制器空操作
    TP框架
    thinkphp基础
    静态缓存
    smarty函数
    Smarty的使用
  • 原文地址:https://www.cnblogs.com/luowentao/p/8977290.html
Copyright © 2011-2022 走看看