Monday, 8 September 2014

You have an array of n elements and a sum. check if 2 elements in the array sum to given sum. Complexity : O(n)

#include <stdio.h>
#include <stdlib.h>
int memory[2000],a[20],sum,n,i,f;
int main()
{
   printf("Enter the number of elements:");
   scanf("%d",&n);

   printf("Enter %d elements:",n);
   for(i=0;i<n;i++)
    scanf("%d",&a[i]);

   printf("Enter the sum of two elements:");
   scanf("%d",&sum);

   for(i=0;i<n;i++)
    if(sum>a[i])
      memory[sum-a[i]]=1;

   for(i=0;i<n;i++)
   if(memory[a[i]]==1){
    f=1;
    printf("Req. elements : %d %d \n",sum-a[i],a[i]);
   }
     if(f==0)
        printf("No such elements exist\n");

    return 0;
}

Sunday, 13 April 2014

code jam: Round 1A 2008_Problem A. Minimum Scalar Product

Problem A. Minimum Scalar Product


Problem
You are given two vectors v1=(x1,x2,...,xn) and v2=(y1,y2,...,yn). The scalar product of these vectors is a single number, calculated as x1y1+x2y2+...+xnyn.
Suppose you are allowed to permute the coordinates of each vector as you wish. Choose two permutations such that the scalar product of your two new vectors is the smallest possible, and output that minimum scalar product.
Input
The first line of the input file contains integer number T - the number of test cases. For each test case, the first line contains integer number n. The next two lines contain n integers each, giving the coordinates of v1 and v2 respectively.
Output
For each test case, output a line
Case #X: Y
where X is the test case number, starting from 1, and Y is the minimum scalar product of all permutations of the two given vectors.
Limits
Small dataset
T = 1000
1 ≤ n ≤ 8
-1000 ≤ xi, yi ≤ 1000
Large dataset
T = 10
100 ≤ n ≤ 800
-100000 ≤ xi, yi ≤ 100000
Sample

Input
 

Output
 
2
3
1 3 -5
-2 4 1
5
1 2 3 4 5
1 0 1 0 1

Case #1: -25
Case #2: 6





Solution:

#include <iostream>
#include<algorithm>
#include <fstream>
using namespace std;

int main()
{int t,n=1,c,i;
long long sum=0,a[805],b[805];
ifstream ip;
ip.open("input.txt");
ofstream op;
op.open("output.txt");

ip>>t;

while(n<=t){
    ip>>c;
    sum=0;
    for(i=0;i<c;i++)
        ip>>a[i];
    for(i=0;i<c;i++)
        ip>>b[i];

        sort(a,a+c);
        sort(b,b+c);

    for(i=0;i<c;i++)
        sum=sum+a[i]*b[c-i-1];

    op<<"Case #"<<n<<": "<<sum<<endl;

 n++;
}

    return 0;
}












code jam: Qualification Round 2014_Problem B. Cookie Clicker Alpha

Problem B. Cookie Clicker Alpha  

Introduction

Cookie Clicker is a Javascript game by Orteil, where players click on a picture of a giant cookie. Clicking on the giant cookie gives them cookies. They can spend those cookies to buy buildings. Those buildings help them get even more cookies. Like this problem, the game is very cookie-focused. This problem has a similar idea, but it does not assume you have played Cookie Clicker. Please don't go play it now: it might be a long time before you come back.

Problem

In this problem, you start with 0 cookies. You gain cookies at a rate of 2 cookies per second, by clicking on a giant cookie. Any time you have at least C cookies, you can buy a cookie farm. Every time you buy a cookie farm, it costs you C cookies and gives you an extra F cookies per second.
Once you have X cookies that you haven't spent on farms, you win! Figure out how long it will take you to win if you use the best possible strategy.

Example

Suppose C=500.0, F=4.0 and X=2000.0. Here's how the best possible strategy plays out:
  1. You start with 0 cookies, but producing 2 cookies per second.
  2. After 250 seconds, you will have C=500 cookies and can buy a farm that produces F=4 cookies per second.
  3. After buying the farm, you have 0 cookies, and your total cookie production is 6 cookies per second.
  4. The next farm will cost 500 cookies, which you can buy after about 83.3333333 seconds.
  5. After buying your second farm, you have 0 cookies, and your total cookie production is 10 cookies per second.
  6. Another farm will cost 500 cookies, which you can buy after 50 seconds.
  7. After buying your third farm, you have 0 cookies, and your total cookie production is 14 cookies per second.
  8. Another farm would cost 500 cookies, but it actually makes sense not to buy it: instead you can just wait until you have X=2000 cookies, which takes about 142.8571429 seconds.
Total time: 250 + 83.3333333 + 50 + 142.8571429 = 526.1904762 seconds. Notice that you get cookies continuously: so 0.1 seconds after the game starts you'll have 0.2 cookies, and π seconds after the game starts you'll have 2π cookies.

Input

The first line of the input gives the number of test cases, T. T lines follow. Each line contains three space-separated real-valued numbers: C, F and X, whose meanings are described earlier in the problem statement.
C, F and X will each consist of at least 1 digit followed by 1 decimal point followed by from 1 to 5 digits. There will be no leading zeroes.

Output

For each test case, output one line containing "Case #x: y", where x is the test case number (starting from 1) and y is the minimum number of seconds it takes before you can have X delicious cookies.
We recommend outputting y to 7 decimal places, but it is not required. y will be considered correct if it is close enough to the correct number: within an absolute or relative error of 10-6. See the FAQ for an explanation of what that means, and what formats of real numbers we accept.

Limits

1 ≤ T ≤ 100.

Small dataset

1 ≤ C ≤ 500.
1 ≤ F ≤ 4.
1 ≤ X ≤ 2000.

Large dataset

1 ≤ C ≤ 10000.
1 ≤ F ≤ 100.
1 ≤ X ≤ 100000.

Sample


Input
 

Output
 
4
30.0 1.0 2.0
30.0 2.0 100.0
30.50000 3.14159 1999.19990
500.0 4.0 2000.0

Case #1: 1.0000000
Case #2: 39.1666667
Case #3: 63.9680013
Case #4: 526.1904762

 Solution:  #include <stdio.h>
int main()
{   int t,n=1;
    double c,f,x,time,t1,t2,r=2,t3=0;
    FILE * fp1 ,*fp2;
    fp1=fopen("input.txt","r");
    fp2=fopen("output.txt","w");

    fscanf(fp1,"%d",&t);

    while(n<=t){
    fscanf(fp1,"%lf%lf%lf",&c,&f,&x);
    r=2;
    time=0;
    t3=0;
    while(1){
        t2=x/r;//142
        t3=c/r;//36
        t1=t3+(x/(f+r));//161

        if(t2<=t1){
            time=time+t2;
            fprintf(fp2,"Case #%d: %lf\n",n,time);
            break;
        }else
        {   time=time+t3;
            r=r+f;

        }
    }n++;



    }


    return 0;
}
 
   

code jam: Qualification Round 2014_Problem A. Magic Trick

Problem A. Magic Trick 

Recently you went to a magic show. You were very impressed by one of the tricks, so you decided to try to figure out the secret behind it!
The magician starts by arranging 16 cards in a square grid: 4 rows of cards, with 4 cards in each row. Each card has a different number from 1 to 16 written on the side that is showing. Next, the magician asks a volunteer to choose a card, and to tell him which row that card is in.
Finally, the magician arranges the 16 cards in a square grid again, possibly in a different order. Once again, he asks the volunteer which row her card is in. With only the answers to these two questions, the magician then correctly determines which card the volunteer chose. Amazing, right?
You decide to write a program to help you understand the magician's technique. The program will be given the two arrangements of the cards, and the volunteer's answers to the two questions: the row number of the selected card in the first arrangement, and the row number of the selected card in the second arrangement. The rows are numbered 1 to 4 from top to bottom.
Your program should determine which card the volunteer chose; or if there is more than one card the volunteer might have chosen (the magician did a bad job); or if there's no card consistent with the volunteer's answers (the volunteer cheated).

Solving this problem

Usually, Google Code Jam problems have 1 Small input and 1 Large input. This problem has only 1 Small input. Once you have solved the Small input, you have finished solving this problem.

Input

The first line of the input gives the number of test cases, T. T test cases follow. Each test case starts with a line containing an integer: the answer to the first question. The next 4 lines represent the first arrangement of the cards: each contains 4 integers, separated by a single space. The next line contains the answer to the second question, and the following four lines contain the second arrangement in the same format.

Output

For each test case, output one line containing "Case #x: y", where x is the test case number (starting from 1).
If there is a single card the volunteer could have chosen, y should be the number on the card. If there are multiple cards the volunteer could have chosen, y should be "Bad magician!", without the quotes. If there are no cards consistent with the volunteer's answers, y should be "Volunteer cheated!", without the quotes. The text needs to be exactly right, so consider copying/pasting it from here.

Limits

1 ≤ T ≤ 100.
1 ≤ both answers ≤ 4.
Each number from 1 to 16 will appear exactly once in each arrangement.

Sample


Input
 

Output
 
3
2
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
3
1 2 5 4
3 11 6 15
9 10 7 12
13 14 8 16
2
1 2 3 4
5 6 7 8
9 10 11 12                 
13 14 15 16
2
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
2
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
3
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

Case #1: 7
Case #2: Bad magician!
Case #3: Volunteer cheated!

 Solution: #include <stdio.h>
int val;
int uniqueEle(int a[] ,int b[]);

int main()
{   FILE * fp1, *fp2;
    int t,a1,a2,c,n=1,i,j;
    int table1[5][5] , table2[5][5];
    fp1=fopen("input.txt","r");
    fp2=fopen("output.txt","w");
    fscanf(fp1,"%d",&t);


    while(n<=t){
      fscanf(fp1,"%d",&a1);
      for(i=0;i<4;i++){
            for(j=0;j<4;j++)
            fscanf(fp1,"%d",&table1[i][j]);

      }

      fscanf(fp1,"%d",&a2);
      for(i=0;i<4;i++){
            for(j=0;j<4;j++)
            fscanf(fp1,"%d",&table2[i][j]);

      }


        c=uniqueEle(table1[a1-1],table2[a2-1]);

        if(c==1)
            fprintf(fp2,"Case #%d: %d\n",n,val);

        else if(c==0)
            fprintf(fp2,"Case #%d: Volunteer cheated!\n",n);

        else
            fprintf(fp2,"Case #%d: Bad magician!\n",n);

    n++;
    }

    return 0;
}




int uniqueEle(int a[],int b[]){
int i,j,c=0;
for(i=0;i<4;i++){
    for(j=0;j<4;j++)
        if(a[i]==b[j]){
            val=a[i];
            c++;
        }


}

return c;
}










 

Tuesday, 4 February 2014

Simulation Of Tower Of Hanoi in java.

The Tower of Hanoi (also called the Tower of Brahma or Lucas' Tower, and sometimes pluralised) is a mathematical game or puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.
The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
  1. Only one disk can be moved at a time.
  2. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
  3. No disk may be placed on top of a smaller disk.
With three disks, the puzzle can be solved in seven moves. The minimum number of moves required to solve a Tower of Hanoi puzzle is 2n - 1, where n is the number of disks.

We Implemented TOH using applets in java.

//CODE:


/*

 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

//package netbeans;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

/**
 *
 * @author Vijay S Y
 */

public class TOH extends Applet implements ItemListener ,ActionListener,Runnable {
boolean first;
Choice from ,to; 
    int[] compArr=new int[]{0,2,0,1,2,1,0,2,1,0,1,2,0,2};
Button submit,reset,plycom;
String clr[]=new String[]{"RED","GREEN","BLUE"};
int f,t,cf,ct;
Thread circleThread;
int tos[]=new int[]{2,-1,-1};
int [][]stack=new int [][]{{2,1,0},
                            {3,3,3},
                            {3,3,3}};

boolean isvalid(){
  print();
  if(ct==t&&cf==f) return true;
   if(tos[t]==-1||stack[f][tos[f]]<stack[t][tos[f]]){  
       tos[t]++;
       stack[t][tos[t]]=stack[f][tos[f]];
       tos[f]--;
        ct=t;
        cf=f;
       return true;
   }

   return false;
}

void print(){
    for(int i=0;i<3;i++)
        System.out.print(tos[i] + "\t");
    System.out.print("\n");
}



@Override
    public void init() {
        setLayout(new FlowLayout(FlowLayout.CENTER));          
           first=false;
           f=t=0;
           ct=cf=5;      
        from =new Choice();
        to= new Choice();
        submit =new Button("SUBMIT");
        reset=new Button("RESET");
        plycom=new Button("COMPUTER_TERN");
       
        from.add("From_A"); to.add("To_A");
        from.add("From_B"); to.add("To_B");
        from.add("From_C");to.add("To_C");
       
        add(from);
        add(to);
        add(submit);
        add(reset);
        add(plycom);
        
        submit.addActionListener((ActionListener) this);
        reset.addActionListener((ActionListener) this);
        plycom.addActionListener((ActionListener) this);
       
        from.addItemListener((ItemListener) this);
        to.addItemListener((ItemListener) this);
       
       
               
    }
   
@Override
    public void itemStateChanged(ItemEvent ie){  
    f = from.getSelectedIndex();
    t=to.getSelectedIndex();
    }
  
    void reset(){
           f=t=0;
                ct=cf=5;
                tos[0]=2;
                tos[1]=-1;
                tos[2]=-1;
                //tos[3]=-1;
               
                stack[0][0]=2;  stack[1][0]=-1;  stack[2][0]=-1;
                stack[0][1]=1;  stack[1][1]=-1;  stack[2][1]=-1;
                stack[0][2]=0;  stack[1][2]=-1;  stack[2][2]=-1;
         
    }
   
@Override
@SuppressWarnings("empty-statement")
    public void actionPerformed(ActionEvent ae){
   
        String str=ae.getActionCommand();
        switch (str) {
            case "SUBMIT":
                repaint();
                break;
            case "RESET":
               reset();
                repaint();
                break;
            case "COMPUTER_TERN":
                System.out.println("in com");
                comp();
               
                break;
                 default:
                break;
        }
       
    }
  
       
       void comp(){
            f=t=0;
                cf=ct=5;
                //*****************************************************************
                tos[0]=2;
                tos[1]=-1;
                tos[2]=-1;
                // tos[3]=-1;
                stack[0][0]=2;  stack[1][0]=-1;  stack[2][0]=-1;
                stack[0][1]=1;  stack[1][1]=-1;  stack[2][1]=-1;
                stack[0][2]=0;  stack[1][2]=-1;  stack[2][2]=-1;
                // stack[0][3]=0;   stack[0][3]=-1;  stack[0][3]=-1;
           circleThread = new Thread((Runnable) this);
         circleThread.start();
             
       }
       
@Override
       public void run(){
        for(int i=0;i<14;i+=2){
            f=compArr[i];
            t=compArr[i+1];
             repaint();
             try {
                  Thread.sleep(1000);
               }
               catch (InterruptedException evt) {}
        }        
          reset();
          repaint();
       }
      
@Override
    public void paint(Graphics g){                       
       //******************************************BASE
           g.fillRoundRect(100, 550-100, 1020 ,20,20,20);
          //*******************************************C1        
          g.fillRoundRect(300, 190, 20,370-100,20,20);
          //********************************************C2
          g.fillRoundRect(600, 190, 20,370-100,20,20);
          //********************************************C3       
          g.fillRoundRect(900, 190, 20,370-100,20,20);
       //*************************************************************************************
      
          if(!isvalid()&&first){
              g.drawString("Invalid Move",450,150);
              first=true;
          }
       //*********************************************************************************************
        for(int i=0;i<=tos[0];i++){
            switch(stack[0][i]){
                case 2:g.setColor(Color.GREEN);
                       break;
                 case 0:g.setColor(Color.BLUE);
                        break;
                 case 1:g.setColor(Color.RED);
                       break;
                     // default:g.setColor(Color.yellow);
            }
          g.fillRoundRect(240-(50*stack[0][i]),530-100-20*i,(100*stack[0][i])+130, 20,20, 20);
        }
      //***************************************************************************************************
        for(int i=0;i<=tos[1];i++){
            switch(stack[1][i]){
                case 2:g.setColor(Color.GREEN);
                       break;
                 case 0:g.setColor(Color.BLUE);
                        break;
                 case 1:g.setColor(Color.RED);
                       break;
                 //default:g.setColor(Color.yellow);
            }
          g.fillRoundRect(540-(50*stack[1][i]),530-100-20*i,(100*stack[1][i])+130, 20,20, 20);
        }
       //*********************************************************************************************
        for(int i=0;i<=tos[2];i++){
            switch(stack[2][i]){
                case 2:g.setColor(Color.GREEN);
                       break;
                 case 0:g.setColor(Color.BLUE);
                        break;
                 case 1:g.setColor(Color.RED);
                       break;
                     // default:g.setColor(Color.yellow);
            }
          g.fillRoundRect(840-(50*stack[2][i]),530-100-20*i,(100*stack[2][i])+130, 20,20,20);
        }
       //***************************************************************************************************
      
       
        
    }
        }
 



//THML FILE