Monday, 16 September 2013

SPOJ IITKWPCO: Create Collections

This blog is intended to discuss many things of which algorithmic problems are a part.
So lets begin with a fairly simple problem Create Collections on spoj:
The problem can easily be solved by hashing as the constraints are really poor. By hashing, we can find out for each number whether a corresponding double number exists or not. Rest is simple :) Below is the accepted code for the problem:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<cstring>
using namespace std;
int hash[10000000];
int main()
{
int t, n, i, a[103], count;
scanf("%d", &t);
while(t--) {
count=0;
memset(hash, 0, sizeof(hash));
scanf("%d", &n);
for(i=0; i<n; i++) {
scanf("%d", &a[i]);
hash[a[i]]+=1;
}
sort(a, a+n);
for(i=0; i<n; i++) {
if(hash[a[i]]>0 && hash[2*a[i]]>0) {
hash[a[i]]--;
hash[2*a[i]]--;
count++;
}
}
printf("%d\n", count);
}
return 0;
}
view raw code.cpp hosted with ❤ by GitHub