题目
标题:倍数问题
【题目描述】
众所周知,小葱同学擅长计算,尤其擅长计算一个数是否是另外一个数的倍数。但小葱只擅长两个数的情况,当有很多个数之后就会比较苦恼。现在小葱给了你 n 个数,希望你从这 n 个数中找到三个数,使得这三个数的和是 K 的倍数,且这个和最大。数据保证一定有解。
【输入格式】
从标准输入读入数据。
第一行包括 2 个正整数 n,?K。
第二行 n 个正整数,代表给定的 n 个数。
【输出格式】
输出到标准输出。
输出一行一个整数代表所求的和。
【样例入】
4 3
1 2 3 4
【样例输出】
9
【样例解释】
选择2、3、4。
【数据约定】
对于 30% 的数据,n <= 100。
对于 60% 的数据,n?<= 1000。
对于另外 20% 的数据,K?<= 10。
对于 100% 的数据,1 <= n?<= 10^5,?1 <= K?<= 10^3,给定的 n 个数均不超过 10^8。
资源约定:
峰值内存消耗(含虚拟机) < 256M
CPU消耗 < 1000ms
请严格按要求输出,不要画蛇添足地打印类似:“请您输入...” 的多余内容。
注意:
main函数需要返回0;
代码
1 #include<iostream> 2 #include<string.h> 3 #include<algorithm> 4 #define nmax 100000 5 using namespace std; 6 int n,k; 7 int a[nmax],maxx=0; 8 int vis[nmax]; 9 bool cmp(int a,int b){ 10 return a>b; 11 } 12 void dfs(int num,int cnt){ 13 if(num%k==0&&cnt==4){ 14 //cout<<num<<endl; 15 if(num>maxx){ 16 maxx=num; 17 } 18 return; 19 }else{ 20 for(int i=0;i<n;i++){ 21 if(vis[i]!=1){ 22 vis[i]=1; 23 //cout<<a[i]<<" "<<cnt<<endl; 24 dfs(num+a[i],cnt+1); 25 vis[i]=0; 26 } 27 } 28 } 29 return; 30 } 31 int main(){ 32 cin>>n>>k; 33 for(int i=0;i<n;i++){ 34 cin>>a[i]; 35 } 36 memset(vis,0,n); 37 sort(a,a+n,cmp); 38 dfs(0,1); 39 cout<<maxx<<endl; 40 41 }
原文:https://www.cnblogs.com/memocean/p/12293026.html