牛客練習33 C Tokitsukaze And Number 【同餘,暴力】
阿新 • • 發佈:2018-12-14
題意:給出整數n,將n的數位重新排列,使得排列後的數字被8整除,並且儘量的大,不包含前導0. n<=10^100.
因為1000≡0(mod 8) 所以一個數x末3位被8整除,則x被8整除.
n<=10^100 字串讀入,並且儲存每個數位的個數.
列舉最後3位數, 判斷n是否有這三個數位後, 將剩下的數位從大到小存到字串,然後直接比較即可.
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> ii; const int N=2e5+5; string str,res; int T,b[11],c[5],flag; void fun(int x){ string a; for(int i=1;i<=3;i++){ b[c[i]]--; if(b[c[i]]<0){ for(int j=1;j<=i;j++) b[c[j]]++; return; } } for(int i=9;i>=0;i--) for(int j=1;j<=b[i];j++) a+=i+'0'; for(int i=3;i>=1;i--) a+=c[i]+'0'; for(int i=1;i<=3;i++) b[c[i]]++; if(a[0]=='0') return; if(res<a) res=a,flag=true; } void check(int x){ int len=0; while(x){ c[++len]=x%10; x/=10; } while(len<3) c[++len]=0; fun(x); } int main(){ ios::sync_with_stdio(false);cin.tie(0); cin>>T; while(T--){ memset(b,0,sizeof(b)); res=""; flag=0; cin>>str; int len=str.length(); if(len==1) { if(str[0]=='8'||str[0]=='0') cout<<str<<'\n'; else cout<<-1<<'\n'; continue; } if(len==2){ int s1=str[0]-'0' + (str[1]-'0')*10; int s2=(str[0]-'0')*10 +str[1]-'0'; int s=-1; if(s1%8==0) s=s1; if(s2%8==0&&s<s2) s=s2; cout<<s<<'\n'; continue; } if(len>=3){ for(int i=0;str[i];i++) b[str[i]-'0']++; for(int i=0;i<1000;i++){ int x=i; if(x%8) continue; check(x); } } if(flag) cout<<res<<'\n'; else cout<<-1<<'\n'; } return 0; }