Consider an arbitrary sequence of integers. One can place + or - operators between integers in the sequence, thus deriving different arithmetical expressions that evaluate to different values. Let us, for example, take the sequence: 17, 5, -21, 15. There are eight possible expressions:
17 + 5 + -21 + 15 = 16
17 + 5 + -21 - 15 = -14
17 + 5 - -21 + 15 = 58
17 + 5 - -21 - 15 = 28
17 - 5 + -21 + 15 = 6
17 - 5 + -21 - 15 = -24
17 - 5 - -21 + 15 = 48
17 - 5 - -21 - 15 = 18
We call the sequence of integers
divisible by
K if + or - operators can be placed between integers in the sequence in such way that resulting value is divisible by
K. In the above example, the sequence is divisible by 7 (17+5+-21-15=-14) but is not divisible by 5.
You are to write a program that will determine divisibility of sequence of integers.
Input
There are multiple test cases, the first line is the number of test cases.
The first line of each test case contains two integers, N and K (1 ≤ N ≤ 10000, 2 ≤ K ≤ 100) separated by a space.
The second line contains a sequence of N integers separated by spaces. Each integer is not greater than 10000 by it's absolute value.
Output
Write to the output file the word "Divisible" if given sequence of integers is divisible by K or "Not divisible" if it's not.
Sample Input
2
4 7
17 5 -21 15
4 5
17 5 -21 15
Sample Output
Divisible
Not divisible
启发:1,涉及整除就要联想取模!!!!!!!!
2,这是有层次性,不要搞混,以下是错误代码
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
freopen("s.txt","r",stdin);
freopen("key.txt","w",stdout);
int testnum;
int num,pos;
cin>>testnum;
int a[101],temp,i,j;
while(testnum--)
{
memset(a,0,sizeof(a));
cin>>num>>pos;
cin>>temp;
temp%=pos;
if(temp<0)temp+=pos;
a[temp]=1;
for(i=1;i<num;i++)
{
cin>>temp;
temp%=pos;
if(temp<0)temp+=pos;//temp%pos¿ÉÄÜÊǸºÊý
for(j=0;j<pos;j++)
{
if(a[j]>0)
{
a[(j+temp)%pos]++;
if((j-temp)<0)
{
a[(j-temp)+pos]++;
}
else
{
a[j-temp]++;
}
if(temp!=0)
a[j]=0;
}
}
}
if(a[0]>0)cout<<"Divisible"<<endl;
else cout<<"Not divisible"<<endl;
}
//system("PAUSE");
return 0;
}
这是有层次性,再添加一个元素时,只能改变前一组a[j]的值
if(a[j]>0)//
{
a[(j+temp)%pos]++;//这里的修改应该不应添加到前面的a[j]中去。
if((j-temp)<0)
所以应当用两个数组。
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
freopen("s.txt","r",stdin);
freopen("key.txt","w",stdout);
int testnum;
int num,pos;
cin>>testnum;
int a[101],temp,i,j;
int b[101];
while(testnum--)
{
memset(a,0,sizeof(a));
memset(a,0,sizeof(b));
cin>>num>>pos;
cin>>temp;
temp%=pos;
if(temp<0)temp+=pos;
a[temp]=1;
for(i=1;i<num;i++)
{
cin>>temp;
temp%=pos;
if(temp<0)temp+=pos;//temp%pos¿ÉÄÜÊǸºÊý
for(j=0;j<pos;j++)
{
if(a[j]>0)
{
b[(j+temp)%pos]++;
if((j-temp)<0)
{
b[(j-temp)+pos]++;
}
else
{
b[j-temp]++;
}
}
}
memset(a,0,sizeof(a));
for(j=0;j<pos;j++)
{
if(b[j]>0)
a[j]=1;
}
memset(b,0,sizeof(b));
}
if(a[0]>0)cout<<"Divisible"<<endl;
else cout<<"Not divisible"<<endl;
}
//system("PAUSE");
return 0;
}
posted on 2009-06-30 22:20
luis 阅读(255)
评论(0) 编辑 收藏 引用