My Weblog

Blog about programming and math

SPOJ 8847. Google is Feeling Lucky

8847. Google is Feeling Lucky is easy problem but you have to be careful if you are using STL sort function. Just parse it , sort it and print all the strings whose values are equal to maximum value. Accepted code.

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

struct ps
	{
		int t;
		string s;
		bool operator<(struct ps p) const
		{
			if (t != p.t) return t<p.t;
			else return false;
		}
	};

vector<struct ps> v;
 int main()
     {
	int t,b,x=1, mx;
	char tmp[200];
	string s,t_1;
	for(scanf("%d\n",&t) ; t>0 ; t--)	
	{
		v.clear();
		for(int i=0;i<10;i++) 
		 {
			getline(cin , s) ;
			sscanf(s.c_str(),"%s %d",tmp , &b);
			t_1 = string( tmp );
			//cout<<t_1<<"-- "<<b<<endl;
			v.push_back((struct ps){ b , t_1 });
		 }
		sort(v.rbegin() , v.rend());		
		mx=v[0].t;
		printf("Case #%d:\n",x++);
		for(int i=0;i<10;i++)
		{
			if(v[i].t == mx ) cout<<v[i].s<<endl;
			else break;
		}
		 
	}
     }

Accepted Haskell code . Thanks to Aditya [ bsrkaditya ] and Tsuyoshi Ito.

import Data.List
import qualified Data.ByteString.Char8 as BS


convert ::[[BS.ByteString]]->[(Int , BS.ByteString)]
convert [] = []
convert (x:xs) = (x_1 , ys ) : convert xs where
	(y:ys:_) = x 
        x_1 = case BS.readInt y of 
		Just ( y' , _) -> y'
		Nothing -> error " inseperable int "

toString ::[(Int , BS.ByteString)] -> BS.ByteString
toString [] = BS.pack "" 
toString [( _ , y )] = y
toString ( x:xs ) = BS.append ( BS.append y ( BS.pack "\n") ) ( toString xs ) where 
	(_ , y) = x 
 


solve::Int -> [BS.ByteString]->[BS.ByteString]
solve _  [] = []
solve t xs = [ BS.append ( BS.append ( BS.append ( BS.pack "Case #")  ( BS.pack.show $ t ) ) ( BS.pack ":\n"))  ans ] ++   solve ( t+1 ) ys 
	where        
		(x,ys) = splitAt 10 xs
		xs' = sortBy (\( a, _ ) ( b, _ ) -> compare b a ). convert . map ( reverse.(BS.words) ) $ x
		m = fst.head $ xs'
		ans' = takeWhile ( \( a , b ) -> a == m ) xs'
        	ans = toString ans'

refine::[BS.ByteString] -> [BS.ByteString]
refine (x:xs) = take (10*k) xs where 
                k = case BS.readInt x of 
			Just ( y' , _ ) -> y'
			Nothing -> error " inseperable int "

main = BS.interact $ BS.unlines. solve 1 .refine . BS.lines
Advertisements

May 24, 2011 - Posted by | Programming

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: