
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
C++ code to check water pouring game has all winner or not
Suppose we have an array A with n elements and have another number s. There is one empty water mug and n non-empty water mugs on the table. In a game, there are few players. In each move, a player takes a non-empty mug of water and pours all water from it into the cup. If it overfills, the player will lost. We have to check whether all of them will be winner or not (the cup will not overfill). If one up is already filled completely, the next player will not play his/her move. Here s is the capacity of the empty cup and A[i] is amount of water present in ith cup.
So, if the input is like A = [3, 1, 3]; s = 4, then the output will be True, because by first and second player, the cup will be filled. For the last one, the player will not play that move.
Steps
To solve this, we will follow these steps −
k := 0 n := size of A sort the array A for initialize i := 0, when i < n - 1, update (increase i by 1), do: k := k + A[i] if k > s, then: return false Otherwise return true
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; bool solve(vector<int> A, int s){ int k = 0; int n = A.size(); sort(A.begin(), A.end()); for (int i = 0; i < n - 1; i++) k += A[i]; if (k > s) return false; else return true; } int main(){ vector<int> A = { 3, 1, 3 }; int s = 4; cout << solve(A, s) << endl; }
Input
{ 3, 1, 3 }, 4
Output
1
- Related Articles
- C++ code to check all bulbs can be turned on or not
- C++ program to check xor game results 0 or not
- C++ code to check string is diverse or not
- C++ code to check grasshopper can reach target or not
- C++ code to check given flag is stripped or not
- C++ code to check pattern is center-symmetrical or not
- C++ code to check given matrix is good or not
- C++ program to find winner of card game
- C++ program to find winner of cell coloring game
- C++ program to find winner of ball removal game
- C++ Program to find winner of unique bidding game
- C++ Program to check joke programming code is generating output or not
- Predict the winner in Coin Game in C++
- C++ Program to find winner name of stick crossing game
- C++ code to check array can be formed from Equal Not-Equal sequence or not
