I made the required changes. Please help me sort out why am I getting wrong answer. The problem was very simple and I used the same logic which was given at the start of the post.
#include<string>
using namespace std;
int main() {
// your code goes here
int T;
cin>>T;
while(T--){
int n,k;
cin>>n>>k;
int A[k];
string S[n];
for(int i = 0; i< k; i++){
cin>>A[i];
}
for(int i = 0; i<n;i++ ){
cin>>S[i];
}
for(int i = 0; i < n; i++){
int sum = 0;
for(int j =0;j<k;j++){
if(S[i][j] == '1'){
sum += A[j];
}
}
cout<<sum<<endl;
}
}
return 0;
}
Yeah, as said by @mittal_sagar , the answer would not fit in an Integer. You should use bigger one, say long or long long. I guess there are no other mistakes.
I used long long, long long int, and even int. But none of them worked. Gave me WA.
Can anyone tell me what’s wrong with my code?
My code:
#include <iostream>
using namespace std;
int main()
{
long long t;
long long n, k;
cin >> t;
long long scr = 0;
while (t--)
{
cin >> n >> k;
long long a[k];
for (size_t i = 0; i < k; i++)
{
cin >> a[i];
}
string s;
for (size_t i = 0; i < n; i++)
{
scr = 0;
cin >> s;
for (size_t j = 0; j < 2; j++)
{
if (s[j] - '0' == 1)
{
scr += a[j];
}
else if (s[j] - '0' == 0)
scr += 0;
}
cout << scr << endl;
}
}
}
Your code will work for test cases
As test cases had situation of 2 questions
What if there are 3 questions and array had 3 elements
I guess your code wont work in that case
I suggest read the problem again
The constraints of N and K were not mentioned separately. What if K = 1000000 and N = 1. It would still satisfy N * K <= 1000000. But most of the solutions would fail if this input is given.
Edit: I meant, if the size of array is statically declared.
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while(T–>0){
int N = sc.nextInt();
int K = sc.nextInt();
long arr[] = new long[K];
for (int i=0; i<K; i++){
arr[i] = sc.nextLong();
}
String []s = new String[N];
for (int i=0; i<N; i++) {
s[i] = sc.next();
}
for (int i=0; i<N; i++){
long out=0;
for (int j=0; j<K; j++) {
if(s[i].charAt(j) == ‘1’){
out += arr[j];
}
}
System.out.println(out);
}
}
}
}