I have a problem : "Multiple test (t test), each test prints all strings with length N and contains exactly H numbers 1."
Here is my code:
#include <iostream>
#include <memory.h>
using namespace std;
typedef long long LL;
LL t,N,H;
LL arr[1000];
bool used[1000];
LL num = 0;
void show(){
LL number = 0;
for (LL u = 0; u<1000; u++)
{
if (arr[u]==2)
{
number++;
}
}
if (number==H)
{
for (LL v = 0; v<1000; v++)
{
if (arr[v])
{
cout << arr[v] - 1;
}
}
cout << "\n";
}
}
void backtrack (LL pos){
if (pos==N+1)
{
num = 0;
show();
return;
}
if (!used[pos])
{
for (LL j = 1; j<=2; j++)
{
if (j==2)
{
if (num==H)
{
break;
}
else
{
num++;
}
}
arr[pos] = j;
used[pos] = true;
backtrack(pos+1);
used[pos] = false;
}
}
}
int main(){
ios::sync_with_stdio(false);
cin >> t;
for (LL i = 0; i<t; i++)
{
cin >> N >> H;
//memset(arr, sizeof(arr), 0);
for (LL cv = 0; cv<1000; cv++)
{
arr[cv] = 0;
}
backtrack(1);
if (i<t-1)
{
cout << "\n";
}
}
return 0;
}
I had trouble with using "memset(arr, sizeof(arr), 0);" - it returned wrong answer. But with the same test, when I used for-loop to assign all elements in array "arr" equal to 0, it returned correct answer.
My test is: 2 4 2 3 1
I am asking to know the difference between memset and for-loop (using for assignment). Thanks.
memset
takes three arguments.The first is the pointer to the block of memory to fill (yourarr
), the second is the value to set, and the third the number of bytes to fill.Here's the documentation for
memset
, if you want to go deeper.In your code I read
That reads as "fill 0 bytes with the value of sizeof".
You've only given the wrong arguments, it sould be: