【codeforces 550C】Divisibility by Eight

weixin_30588675發表於2020-04-05

time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given a non-negative integer n, its decimal representation consists of at most 100 digits and doesn’t contain leading zeroes.

Your task is to determine if it is possible in this case to remove some of the digits (possibly not remove any digit at all) so that the result contains at least one digit, forms a non-negative integer, doesn’t have leading zeroes and is divisible by 8. After the removing, it is forbidden to rearrange the digits.

If a solution exists, you should print it.

Input
The single line of the input contains a non-negative integer n. The representation of number n doesn’t contain any leading zeroes and its length doesn’t exceed 100 digits.

Output
Print “NO” (without quotes), if there is no such way to remove some digits from number n.

Otherwise, print “YES” in the first line and the resulting number after removing digits from number n in the second line. The printed number must be divisible by 8.

If there are multiple possible answers, you may print any of them.

Examples
input
3454
output
YES
344
input
10
output
YES
0
input
111111
output
NO

【題目連結】:http://codeforces.com/contest/550/problem/C

【題解】

假設一個數為x
設x的位數大於等於4

x=1000*a1+100*a2+10*a3+a4
而1000能被8整除
則x能被8整除的充要條件是x的後3位也能被8整除;
因為位數最大為100
所以C(100,3)->取出3個數看看能不能是8的倍數;
當然不能漏了2位數和一位數的情況;
都列舉出來即可;

【完整程式碼】

#include <bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define rei(x) scanf("%d",&x)
#define rel(x) scanf("%I64d",&x)

typedef pair<int,int> pii;
typedef pair<LL,LL> pll;

//const int MAXN = x;
const int dx[9] = {0,1,-1,0,0,-1,-1,1,1};
const int dy[9] = {0,0,0,-1,1,-1,1,-1,1};
const double pi = acos(-1.0);

const int MAXN = 1E2+10;

char s[MAXN];
bool bo[MAXN];
int n,limit;

void sear_ch(int now,int pre)
{
    if (now == limit+1)
    {
        int tt = 0;
        rep1(i,1,100)
            if (bo[i])
            {
                int key = s[i]-'0';
                tt = tt * 10 + key;
            }
        if (tt % 8 == 0)
        {
            puts("YES");
            printf("%d\n",tt);
            exit(0);
        }
        return;
    }
    rep1(i,pre+1,n)
        if (!bo[i])
        {
            bo[i] = true;
            sear_ch(now+1,pre);
            bo[i] = false;
        }
}

int main()
{
    //freopen("F:\\rush.txt","r",stdin);
    scanf("%s",s+1);
    n = strlen(s+1);
    limit = 3;
    sear_ch(1,0);
    limit = 2;
    sear_ch(1,0);
    limit = 1;
    sear_ch(1,0);
    puts("NO");
    return 0;
}

轉載於:https://www.cnblogs.com/AWCXV/p/7626787.html

相關文章