CSP-S 2019 格雷码

题面

 

 题解

 这道题,它都把格雷码的计算方法告诉我们了,所以真的只是个模拟题,

两种解法:①long long从负数存,要特判

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#define LL long long
using namespace std;
LL cnt = 1,k2 = 0;
LL read() {
    LL f = 1,x2 = -9223372036854775808ll,x = 0;char s = getchar();
    while(s < '0' || s > '9') {if(s == '-')f = -1;s = getchar();}
    while(s >= '0' && s <= '9') {
        if(x >= 1e16) {
            cnt *= 10ll;
            k2 = k2 * 10ll + s - '0';
        }
        else x = x * 10 + s - '0';
        s = getchar();
    }
    if(cnt > 1) {
        cnt /= 10ll;
        x2 += k2;
        x2 += x * cnt;
        x2 += x * cnt;
        x2 += x * cnt;
        x2 += x * cnt;
        x2 += x * cnt;
        x2 += x * cnt;
        x2 += x * cnt;
        x2 += x * cnt;
        x2 += x * cnt;
        x2 += x * cnt;
    }
    else x2 += x * cnt + k2;
    return x2;
}
LL n,m,i,j,s,o,k;
bool flag = 0;
void dfs(LL n,LL k) {
//  printf("\n%lld %lld\n",n,k);
    if(n == 1) {
        printf("%d",(k + 9223372036854775807ll + 1ll) & 1ll);
        return ;
    }
    if(((k*1ll) > 1ll*((-9223372036854775808ll) + (1ll<<(n-2ll)) - 1ll + ((1ll<<(n-2ll)))) && !flag) || ((k*1ll) >= 1ll*((-9223372036854775808ll) + (1ll<<(n-2ll)) + ((1ll<<(n-2ll)))) && flag)) {
        putchar('1');
        k = k - (1ll<<(n-2ll));
        k = k - ((1ll<<(n-2ll)) - 1ll);
        return dfs(n - 1ll,(1ll<<(n - 2ll)) + (-9223372036854775808ll) + (1ll<<(n-2ll)) - k + (-9223372036854775808ll));
    }
    else {
        putchar('0');
        return dfs(n - 1ll,k);
    }
}
int main() {
//  freopen("code.in","r",stdin);
//  freopen("code.out","w",stdout);
    scanf("%lld",&n);
    k = read();
    if(k >= 0) flag = 1;
//  printf("%lld %lld\n, %d",k*1ll,1ll*((-9223372036854775808ll) + (1ll<<(n-2ll)) - 1ll + ((1ll<<(n-2ll)))),(k*1ll) > 1ll*((-9223372036854775808ll) + (1ll<<(n-2ll)) - 1ll + ((1ll<<(n-2ll)))));
    dfs(n,k);putchar('\n');
    return 0;
}

②(官方题解做法)用 unsigned long long :

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#define LL unsigned long long
#define Un unsigned
using namespace std;
LL read() {
    LL f = 1,x = 0;char s = getchar();
    while(s < '0' || s > '9') {if(s == '-')f = -1;s = getchar();}
    while(s >= '0' && s <= '9') {
        x = x * 10 + s - '0';
        s = getchar();
    }
    return x;
}
LL n,m,i,j,s,o,k;
void dfs(LL n,LL k) {
    if(n == 1) {
        printf("%d",k & 1ll);
        return ;
    }
    if(k > (LL)((LL)(1ll)<<(n-1ll)) - (LL)(1ll)) {
        putchar('1');
        return dfs(n - 1ll,(LL)((LL)(1ll)<<(n-1ll)) - (LL)(1ll) + (LL)((LL)(1ll)<<(n-1ll)) - k);
    }
    else {
        putchar('0');
        return dfs(n - 1ll,k);
    }
}
int main() {
//  freopen("code.in","r",stdin);
//  freopen("code.out","w",stdout);
    scanf("%llu",&n);
    k = read();
    dfs(n,k);putchar('\n');
    return 0;
}

 

posted @ 2019-11-19 08:29  DD_XYX  阅读(70)  评论(0编辑  收藏  举报