Codeforces - 1300C ( 位运算 )

Codeforces - 1300C ( 位运算 )

题目链接:http://codeforces.com/contest/1300/problem/C

题意:

定义:    ,

给长度为n的一个序列 问如何排列, 的值最大

输出对应的序列.

思路:位运算,所以我们化成二进制后一位一位的来看,先看1位时,容易发现只有答案是1,推广到多层也适用,只有a1是1,a2a3a4...an都为0时才对答案有贡献。

这样我们只需要找到,位数最高且只有一个数在此位为1的数,放到a1的位置,得到的答案一定是最大的。

代码:

#include

using namespace std;

int via[100];
int ok[100];
int a[100005];

int main()
{
    int n,x;
    cin >> n;
    for ( int i=1; i<=n; i++ ) {
        scanf("%d",&x);a[i]=x;
        int cnt = 1;
        while ( x>0 ) {
            if ( x%2==1 ) {
                if ( via[cnt]==0 ) via[cnt]=i,ok[cnt]=1;
                else ok[cnt]=0;
            }
            x /= 2;
            cnt ++;
        }
    }
    for ( int i=40; i>=1; i-- ) {
        if ( ok[i]==1 ) {
            printf("%d",a[via[i]] );
            for ( int j=1; j<=n; j++ ) {
                if ( j==via[i] ) continue;
                printf(" %d",a[j]);
            }
            printf("\n");
            return 0;
        }
    }
    printf("%d",a[1] );
    for ( int i=2; i<=n; i++ ) {
        printf(" %d",a[i]);
    }
    printf("\n");

    return 0;
}

 

你可能感兴趣的:(CodeForces,Div.2)