AtCoder Beginner Contest 167 B I will explain the problem "Easy Linear Programming".
Problem URL: https://atcoder.jp/contests/abc167/tasks/abc167_b
There are $ A $ cards with $ 1 $, $ B $ cards with $ 0 $, and $ C $ cards with $ -1 $. Answer some of the maximum possible sums of the numbers written on the cards you took when you picked just $ K $ from these cards.
・ All inputs are integers ・ $ 0 \ leq A, B, C $ ・ $ 1 \ leq K \ leq A + B + C \ leq 2 × 10 ^ 9 $
To make the maximum value as large as possible </ b>, the card is taken according to the value of $ K $ as follows.
For $ K \ leq A $ All you have to do is select and take a card with $ 1 $ written on it.
If $ A <K \ leq A + B $ After performing the method shown in 1., select the card with the remaining $ (K-A) $ $ 0 $ written on it.
If $ A + B <K \ leq A + B + C $ After performing the method shown in 2., select the card with the remaining $ (K-A-B) $ $ -1 $ written on it.
In case of 1. The answer is $ K $ In case 2. The answer is $ A $ In case of 3, the answer is $ A- (K-A-B) $ It will be.
You can change the output of the answer depending on the value of $ K $.
In addition, there are restrictions
type (C ++ or Java) <font color = "red"> $ -2 ^ {31} $ ~ $ 2 ^ {31} -1 $ </ font>, Since $ 2 ^ {31} = 21474883647 $, Within the constraints, it's okay to define $ K $ as an ʻint
type.
Below are examples of solutions in Python3, C ++, and Java.
{ABC167B.py}
A,B,C,K = map(int,input().split())
if (K <= A):
print(K)
elif (A < K <= A+B):
print(A)
else:
print(A-(K-A-B))
{ABC167B.cpp}
#include<bits/stdc++.h>
using namespace std;
int main(){
int a,b,c,k;
cin >> a >> b >> c >> k;
if (k <= a){
cout << k << endl;
}else if (k <= a+b){
cout << a << endl;
}else{
cout << a-(k-a-b) << endl;
}
}
{ABC167B.java}
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
int b = scan.nextInt();
int c = scan.nextInt();
int k = scan.nextInt();
if (k <= a){
System.out.println(k);
}else if (k <= a+b){
System.out.println(a);
}else{
System.out.println(a-(k-a-b));
}
}
}
Recommended Posts