Tuesday, January 7, 2014

codechef STONES - "jewels and stones" solution

codechef STONES - "jewels and stones": http://www.codechef.com/problems/STONES

codechef STONES - "jewels and stones" solution: http://ideone.com/PTV8oU

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

int main() {
int t, cnt;
char j[105], s[105];
scanf("%d", &t);
while(t--) {
cnt=0;
scanf("%s\n%s", &j, &s);
for(int k=0; k<strlen(s); k++) for(int i=0; i<strlen(j); i++) if(s[k]==j[i]) { cnt++; break; }
printf("%d\n", cnt);
}
return 0;
}

codechef STONES - "jewels and stones" guidance: 

when you first look at the problem, you think of looping from jewels to stones, you take every item of jewel and compare it with every item in the stones, if they are equal, you increment your count(cnt++). however, you have to look backwards, thus, take every item of stone and compare it with jewels, if they are equal, increment count(cnt++) and break the inner loop(loop of jewels), by doing so you automatically pass to the next item in stones(s[k++]).

No comments:

Post a Comment