Google Code Jam – Template Javascript by vudduu

vudduu: Me gusta mucho usar este template en multiples competencias y para probar la solución a problemas creados para nacionales y concursos online en Bolivia.

var HackerX = (function(){
	var vIn = [],
		itIn = 0;

	var getNext = function() {
		return vIn[itIn++];
	};

	return {
		processData: function(input) {
			var inArray = input.split('n');
		    for(var it = 0; it<inArray.length ;it++) {
		    	inArray[it].split(' ').forEach(function(item) {
		    		vIn.push(item);
		    	});
		    }
		},

		solveAll: function() {
            var T = getNext(), res;
			for(var cas=1; cas<=T ;cas++) {
                // solve
                console.log(["Case #", cas, ":"].join(''), res);
            }
		}
	}
})();

process.stdin.resume();
process.stdin.setEncoding("ascii");
var _input = "";
process.stdin.on("data", function (input) {
    _input += input;
});
process.stdin.on("end", function () {
   HackerX.processData(_input);
   HackerX.solveAll();
});

Para correr utilizo el siguiente comando en mi terminal:

node a.js < input.txt

 

Google Code Jam – Template Java by vudduu

vudduu: No utilizo Java todo el tiempo, pero cuando lo hago utilizo el siguiente template.

import java.math.*;
import java.util.*;
import java.io.*;

public class D {

	void solve() throws IOException{
		int t = nextInt(), m;
		for(int i = 0; i < t; i++) {
			m = nextInt();
			int res = 0;

			System.out.println("Case #" + (i+1) + ": " + res);
		}
	}

	BufferedReader reader;
	StringTokenizer tokenizer;
	PrintWriter writer;

    void run() throws IOException {
		//in = new BufferedReader(new InputStreamReader(System.in));
		out = new PrintWriter(System.out);
		in = new BufferedReader(new FileReader("D.in"));
		//out.println("output.txt");
		solve();
		out.close();
	}

	public static void main(String[] args) throws IOException {
		new D().run();
	}

	BufferedReader in;
	StringTokenizer str;
	PrintWriter out;

	String next() throws IOException {
		while ((str == null) || (!str.hasMoreTokens())) {
			str = new StringTokenizer(in.readLine());
		}
		return str.nextToken();
	}

	int nextInt() throws IOException {
		return Integer.parseInt(next());
	}

}

 

Google Code Jam – Template Objective-C by vudduu

vudduu: …

#import <Foundation/Foundation.h>
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <string.h>

#define FOR(i,a,b)  for(int i=(a),_##i=(b);i<_##i;++i)
#define F(i,a)      FOR(i,0,a)
#define ALL(x)      x.begin(),x.end()
#define PB          push_back
#define MP          make_pair
typedef long long   LL;

char mapa[300];

@interface ClassSolve:NSObject{

}
- (void) solve;
@end

@implementation ClassSolve
	-(id) init {
		self = [super init];

		return self;
	}
	- (void) solve {
		int res;

		printf("%dn", res);
	}
@end

int main(int argc, const char * argv[]) {
	@autoreleasepool {
		freopen("/Users/edwinguzman/Downloads/a.in", "r", stdin);
		//freopen("/Users/edwinguzman/Downloads/A-small-attempt0.in.txt", "r", stdin);
		freopen("/Users/edwinguzman/Downloads/a.out", "w", stdout);
		int T;
		scanf("%d", &T);
		gets(A);
		F(cas, T){
			ClassSolve *class = [[ClassSolve alloc] init];
			printf("Case #%d: ", cas+1);
			[class solve];
		}
	}
	return 0;
}

 

Google Code Jam – Template Python by urupica

urupica: …

#!/usr/bin/python

'''
' Python template for Google Code Jam
' Version 0.2
'
' By urupica (Kevin Bauer) urupica@gmail.com
'
' Usage: $ ./google.py inputFile [outputFile]
' Script reads from inputFile and writes to outputFile (optional)
'
' Use at own risk. Use the code for whatever you like 🙂
'''

# Import necessary libraries to read command line arguments and calculate execution time
import sys, datetime

# Import third-party libraries (optional)
# https://code.google.com/p/gmpy/
#import gmpy

def solve():
    '''
    ' Write your code here
    ' Return solution
    '''
    pass

def main():
    # Test if at least input file is provided
    if len(sys.argv) < 2:
        print 'Please provide input file'
        print 'Usage: %s inputfile [outputfile]' % sys.argv[0]
        return
    # Start time
    timestart = datetime.datetime.now()

    # Open input and output files
    try:
        inputFile = open(sys.argv[1])
    except:
        print 'Failed to read input file %s' % sys.argv[1]
        return
    try:
        outputFile = open(sys.argv[2], 'w') if len(sys.argv) >= 3 else None
    except:
        print 'Failed to create output file %s' % sys.argv[2]
        return

    # First line of input file usually is the number of test cases.
    # Adjust if necessary
    testCases = int(inputFile.readline().strip())

    # Display number of test cases and output file name 
    print '-----------------'
    print 'Test cases: %d ' % testCases
    print 'No output file' if len(sys.argv) < 3 else 'Writing to %s' % sys.argv[2]
    print '-----------------'

    # Loop through all test cases
    for testCaseNumber in range(1, testCases+1):

        '''
        ' Edit this section
        ' Read Test Case input and adjust output format
        ' Uncomment the necessary parts and adjust to your needs
        '''

        '''
        ' Integers
        '''
        # Read an integer
        #n = int(inputFile.readline().strip())

        # Read a list of integers
        #n_list = map(int, inputFile.readline().strip().split())

        # Read a matrix of integers
        #n_matrix = []
        #for i in range(n):
        #    n_matrix.append(map(int, inputFile.readline().strip().split()))

        '''
        ' Floats
        '''
        # Read a float
        #f = float(inputFile.readline().strip())

        # Read a list of flots
        #f_list = map(float, inputFile.readline().strip().split())

        '''
        ' Strings
        '''
        # Read a string
        # s = inputFile.readline().strip()

        # Read a list of strings
        # s_list = inputFile.readline().strip().split()

        '''
        ' Return string.
        ' Add necessary arguments to solve() function
        ' Adjust return type if necessary (%s for string, %f for floats, etc)
        '''
        string = 'Case #%d: %d' % (testCaseNumber, solve())

        '''
        ' End of edit section
        '''

        # print return string and write it to output file
        print string
        if outputFile:
            outputFile.write(string + 'n')

    # Print some final info: output file name and execution time
    print '-----------------'
    print 'Written to %s' % sys.argv[2] if outputFile else 'No output file'
    print 'Elapsed time: %s' % (datetime.datetime.now() - timestart)
    print '-----------------'

    # Close input and output files
    inputFile.close()
    if outputFile:
        outputFile.close()

if __name__=='__main__':
    main()

 

Google Code Jam – Template C++ by vudduu

vudduu: Este es el template de C++ que me gusta usar, pero mas que todo con el que me siento comodo en las rondas del codejam.

#include <iostream>
#include <sstream>
#include <utility>
#include <cstdlib>
#include <cstdio>
#include <cctype>
#include <cmath>
#include <functional>
#include <algorithm>
#include <numeric>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <stdio.h>
#include <string.h>
using namespace std;

#define FOR(i,a,b)  for(int i=(a),_##i=(b);i<_##i;++i)
#define F(i,a)      FOR(i,0,a)
#define ALL(x)      x.begin(),x.end()
#define PB          push_back
#define MP          make_pair
#define S           size()
typedef long long   LL;

bool solve() {

}

int main() {
    freopen("a.txt", "r", stdin);
    // freopen("small-input.txt", "r", stdin);
    int T;
    scanf("%d", &T);
    for(int cas=1; cas<=T ;cas++) {
        printf("Case #%d: ", cas);
        if(solve()) printf("YESn");
        else printf("NOn");
    }
}

Antes de cada competencia es bueno saber cuantas operaciones pueden realizar por segundo en sus equipos. Como Gareve dice necesitamos conocer ese numero magico que seria nuestro tope.

En C++ pueden obtener este numero magico ejecutando el siguiente código.

#include <iostream>
#include <time.h>
using namespace std;

int main() {
    double ini = clock();
    int c = 0;
    while(double(clock()-ini)/1000000.0 < 1.0)
        c++;
    cout<<"operaciones: "<< c << " " << double(clock()-ini)/1000000.0 << endl;
}