codeforce 550c Divisibility by Eight (DFS)

http://codeforces.com/contest/550/problem/C

C. Divisibility by Eight

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.

Sample test(s)
input
3454
output
YES
344
input
10
output
YES
0
input
111111
output
NO

从给出的这个数中剔除某些位数,使剩下的位数组成的数字能被8整除,剔除后的数字不能打乱顺序

能被8整除的数的后三位组成的数一定能被8整除

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <limits>
#include <queue>
#include <stack>
#include <vector>
#include <map>

using namespace std;
typedef long long LL;

#define N 810
#define INF 0x3f3f3f3f
#define PI acos (-1.0)
#define EPS 1e-5
#define MOD 10007
#define met(a, b) memset (a, b, sizeof (a))

int n, ans, len;
LL cnt;
char str[N];

void DFS (int sa, int en, int num, LL sum)
{
    if (sum % 8 == 0 && num <= 3)
    {
        ans++;
        cnt = sum;
        return;
    }

    if (num > 3) return;

    for (int i=en+1; i<len; i++)
        DFS (sa, i, num+1, sum*10+str[i]-'0');
    return;
}

int main ()
{
    while (scanf ("%s", str) != EOF)
    {
        len = strlen (str);
        ans = 0;

        for (int i=0; i<len; i++)
        {
            DFS (i, i, 1, str[i]-'0');
            if (ans) break;
        }

        if (!ans) puts ("NO");
        else
        {
            puts ("YES");
            printf ("%lld\n", cnt);
        }
    }
    return 0;
}


你可能感兴趣的:(codeforce 550c Divisibility by Eight (DFS))