题目链接:https://ac.nowcoder.com/acm/contest/308/C

       首先我们要知道8的倍数有什么特征,一个数的后三位是8的倍数,这个数就是8的倍数,所以我们就去按照这个思路去模拟,我们枚举所有8的倍数,当作这个数的后三位,然后判断是否能排成这个数然后求一个最大数就好了,直接看代码吧,不难理解。


AC代码:

#include <bits/stdc++.h>
using namespace std;
int T;

int main()
{
	scanf("%d",&T);
	while(T--){
		string str, ch;
		cin>>str;
		int len = str.length();
		if(len == 1){
			if((str[0] - '0') % 8 != 0) puts("-1");
			else cout<<str<<endl;
			continue;
		}
		if(len == 2){
			int xx = (str[0] - '0') * 10 + (str[1] - '0');
			int yy = (str[1] - '0') * 10 + (str[0] - '0');
			if(xx % 8 != 0 && yy % 8 != 0) puts("-1");
			if(xx % 8 != 0 && yy % 8 == 0) cout<<yy<<endl;
			if(xx % 8 == 0 && yy % 8 != 0) cout<<xx<<endl;
			if(xx % 8 == 0 && yy % 8 == 0) cout<<max(xx, yy)<<endl;
			continue;
		}
		if(len > 2){
			string ans;
			map<int,int> ma;
			for(int i=0;i<len;i++) ma[(str[i] - '0')] ++;
			for(int i=0;i<1000;i+=8){
				string ch;
				int xx = i / 100, yy = i / 10 % 10, zz = i % 10;
				ma[xx] --; ma[yy] --; ma[zz] --;
				if(ma[xx] >= 0 && ma[yy] >= 0 && ma[zz] >= 0){
					for(int j=9;j>=0;j--){
						for(int k=0;k<ma[j];k++) ch += (j + '0');
					}
					ch += (xx + '0'); ch += (yy + '0'); ch += (zz + '0');
					ans = max(ans, ch);
				}
				ma[xx] ++; ma[yy] ++; ma[zz] ++;
			}
			if(ans == "") puts("-1");
			else cout<<ans<<endl;
		}
	}
	return 0;
}