Thursday, June 4, 2015

Codeforces Round #223 (Div. 2) 381A Sereja and Dima

Solution to Codeforces Round #223 (Div. 2) 381A Sereja and Dima with explanation

           Kindly comment if you have any other best solution or found any errors in my program.

Explanation:
       This program uses greedy technique i.e. each player wants to take a card with high score.

Steps:
  • Get the score of n cards in an array.
  • Let i and j points to start and end of the array respectively.
  • Then compare i and j to and choose the maximum of both.
  • Add the choosen cards score to the corresponding player.
  • The player turn can be identified by variable 'k' . If k is even player 1 turn, otherwise player 2 turn.
  • Continue until i and j crosses each other.


Program:

//    Accepted                                                                                            31ms                             4KB




#include<iostream>

using namespace std;
int main()
{
    int n;
    cin>>n;
    int a[n];
    for(int i=0;i<n;i++)
        cin>>a[i];
    int i=0,j=n-1,max,k=0;
    int play1=0,play2=0;
    while(i<=j)
    {
        if(a[i]>=a[j])
        {
           max=a[i];
           i++;
        }
        else{
            max=a[j];
            j--;
        }
        if(k%2==0)
          play1=play1+max;
        else
          play2=play2+max;
     k++;
    }
    cout<<play1<<" "<<play2<<endl;
    return 0;

}

No comments:

Post a Comment