Instruction
stringlengths 261
35k
| Response
stringclasses 1
value |
---|---|
For this Question: Given a number N, find the value of the below Equation for the given number.
Equation: -
N
∑ {(X - 1)<sup>3</sup> + 3(X + 1)<sup>2</sup> + 2}
X = 1<b>User task:</b>
Since this is a functional problem, you don’t have to worry about the input, you just have to complete the function <b>equationSum()</b>, where you will get N as a parameter.
<b>Constraints:</b>
1 <= N <= 100Return the sum of equation.Sample Input:-
1
Sample Output:-
14
Sample Input:-
2
Sample Output:-
44, I have written this Solution Code: int equationSum(int n){
int sum=n*(n+1);
sum=sum/2;
sum=sum*sum;
sum+=9*((n*(n+1))/2);
sum+=4*(n);
return sum;
}
, In this Programming Language: C, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a number N, find the value of the below Equation for the given number.
Equation: -
N
∑ {(X - 1)<sup>3</sup> + 3(X + 1)<sup>2</sup> + 2}
X = 1<b>User task:</b>
Since this is a functional problem, you don’t have to worry about the input, you just have to complete the function <b>equationSum()</b>, where you will get N as a parameter.
<b>Constraints:</b>
1 <= N <= 100Return the sum of equation.Sample Input:-
1
Sample Output:-
14
Sample Input:-
2
Sample Output:-
44, I have written this Solution Code: int equationSum(int n){
int sum=n*(n+1);
sum=sum/2;
sum=sum*sum;
sum+=9*((n*(n+1))/2);
sum+=4*(n);
return sum;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer array A of size N, find the minimum absolute difference between any two elements in the array.
We define the absolute difference between two elements ai and aj (where i != j ) is |ai - aj|.First line of input contains a single integer N, next line contains N space separated integers containing values of array A.
Constraints :
2 < = N < = 10^5
0 < = A[i] < = 10^10Print the minimum absolute difference between any two elements of the array.Sample Input :
5
2 9 0 4 5
Sample Input :
1
Sample Input:-
3
1 2 1
Sample Output:-
0, I have written this Solution Code: import math
import os
import random
import re
import sys
def minimumAbsoluteDifference(arr):
diff_arr = []
sort_arr = sorted(arr)
for i in range(0, len(sort_arr)-1):
diff_arr.append(abs(sort_arr[i] - sort_arr[i+1]))
return min(diff_arr)
if __name__ == '__main__':
n=int(input())
n=input().split()
for i in range(len(n)):
n[i]=int(n[i])
print(minimumAbsoluteDifference(n)%(10**9+7)), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer array A of size N, find the minimum absolute difference between any two elements in the array.
We define the absolute difference between two elements ai and aj (where i != j ) is |ai - aj|.First line of input contains a single integer N, next line contains N space separated integers containing values of array A.
Constraints :
2 < = N < = 10^5
0 < = A[i] < = 10^10Print the minimum absolute difference between any two elements of the array.Sample Input :
5
2 9 0 4 5
Sample Input :
1
Sample Input:-
3
1 2 1
Sample Output:-
0, I have written this Solution Code: import java.io.*; // for handling input/output
import java.util.*; // contains Collections framework
// don't change the name of this class
// you can add inner classes if needed
class Main {
public static void main (String[] args) {
// Your code here
Scanner sc = new Scanner(System.in);
int arrSize = sc.nextInt();
long arr[]= new long[arrSize];
for(int i = 0; i < arrSize; i++)
arr[i] = sc.nextLong();
System.out.println(minABSDiff(arr, arrSize));
}
static long minABSDiff(long arr[], int arrSize)
{
Arrays.sort(arr);
long ans=Long.MAX_VALUE;
for(int i = 1; i < arrSize; i++){
ans = Math.min(ans,arr[i]-arr[i-1]);}
return ans;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer array A of size N, find the minimum absolute difference between any two elements in the array.
We define the absolute difference between two elements ai and aj (where i != j ) is |ai - aj|.First line of input contains a single integer N, next line contains N space separated integers containing values of array A.
Constraints :
2 < = N < = 10^5
0 < = A[i] < = 10^10Print the minimum absolute difference between any two elements of the array.Sample Input :
5
2 9 0 4 5
Sample Input :
1
Sample Input:-
3
1 2 1
Sample Output:-
0, I have written this Solution Code:
// author-Shivam gupta
#include <bits/stdc++.h>
using namespace std;
#define MEM(a, b) memset(a, (b), sizeof(a))
#define FOREACH(it, l) for (auto it = l.begin(); it != l.end(); it++)
#define IN(A, B, C) assert( B <= A && A <= C)
#define MP make_pair
#define FOR(i,a) for(int i=0;i<a;i++)
#define FOR1(i,j,a) for(int i=j;i<a;i++)
#define EB emplace_back
#define INF (int)1e9
#define EPS 1e-9
#define PI 3.1415926535897932384626433832795
#define MOD 1000000007
const int N = 3e5+5;
#define read(type) readInt<type>()
#define max1 20000001
#define out(x) cout<<x<<'\n'
#define out1(x) cout<<x<<" "
#define END cout<<'\n'
#define int long long int
signed main()
{
int n;
cin>>n;
int a[n];
FOR(i,n){
cin>>a[i];}
sort(a,a+n);
int ans=LONG_MAX;
FOR1(i,1,n){
ans=min(ans,a[i]-a[i-1]);}
out(ans);
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a sorted array arr[] of N integers and a number K is given. The task is to check if the element K is present in the array or not.
<b>Note:</b> Use binary search to solve the problemThe first line of input contains a number of test cases T. For each test case, the first line of input contains a number of elements in the array, and the number K is separated by space. The next line contains N elements.
<b>Constraints:</b>
1 ≤ T ≤ 10
1 ≤ N ≤ 10<sup>5</sup>
1 ≤ K ≤ 10<sup>9</sup>
1 ≤ arr[i] ≤ 10<sup>9</sup>
<b>Sum of N over all test cases doesn't exceed 10<sup>6</sup></b>If the element is present in the array print "1" else print "-1".Sample Input:
2
5 6
1 2 3 4 6
5 2
1 3 4 5 6
Sample Output:
1
-1, I have written this Solution Code: static int isPresent(long arr[], int n, long k)
{
int left = 0;
int right = n-1;
int res = -1;
while(left<=right){
int mid = (left+right)/2;
if(arr[mid] == k){
res = 1;
break;
}else if(arr[mid] < k){
left = mid + 1;
}else{
right = mid - 1;
}
}
return res;
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a sorted array arr[] of N integers and a number K is given. The task is to check if the element K is present in the array or not.
<b>Note:</b> Use binary search to solve the problemThe first line of input contains a number of test cases T. For each test case, the first line of input contains a number of elements in the array, and the number K is separated by space. The next line contains N elements.
<b>Constraints:</b>
1 ≤ T ≤ 10
1 ≤ N ≤ 10<sup>5</sup>
1 ≤ K ≤ 10<sup>9</sup>
1 ≤ arr[i] ≤ 10<sup>9</sup>
<b>Sum of N over all test cases doesn't exceed 10<sup>6</sup></b>If the element is present in the array print "1" else print "-1".Sample Input:
2
5 6
1 2 3 4 6
5 2
1 3 4 5 6
Sample Output:
1
-1, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
unordered_map<long long,int> m;
long k;
cin>>k;
long long a;
for(int i=0;i<n;i++){
cin>>a;
m[a]++;
}
if(m.find(k)!=m.end()){
cout<<1<<endl;
}
else{
cout<<-1<<endl;
}
}
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a sorted array arr[] of N integers and a number K is given. The task is to check if the element K is present in the array or not.
<b>Note:</b> Use binary search to solve the problemThe first line of input contains a number of test cases T. For each test case, the first line of input contains a number of elements in the array, and the number K is separated by space. The next line contains N elements.
<b>Constraints:</b>
1 ≤ T ≤ 10
1 ≤ N ≤ 10<sup>5</sup>
1 ≤ K ≤ 10<sup>9</sup>
1 ≤ arr[i] ≤ 10<sup>9</sup>
<b>Sum of N over all test cases doesn't exceed 10<sup>6</sup></b>If the element is present in the array print "1" else print "-1".Sample Input:
2
5 6
1 2 3 4 6
5 2
1 3 4 5 6
Sample Output:
1
-1, I have written this Solution Code: def binary_search(arr, low, high, x):
if high >= low:
mid = (high + low) // 2
if arr[mid] == x:
return 1
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
else:
return binary_search(arr, mid + 1, high, x)
else:
return -1
def position(n,arr,x):
return binary_search(arr,0,n-1,x)
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a sorted array arr[] of N integers and a number K is given. The task is to check if the element K is present in the array or not.
<b>Note:</b> Use binary search to solve the problemThe first line of input contains a number of test cases T. For each test case, the first line of input contains a number of elements in the array, and the number K is separated by space. The next line contains N elements.
<b>Constraints:</b>
1 ≤ T ≤ 10
1 ≤ N ≤ 10<sup>5</sup>
1 ≤ K ≤ 10<sup>9</sup>
1 ≤ arr[i] ≤ 10<sup>9</sup>
<b>Sum of N over all test cases doesn't exceed 10<sup>6</sup></b>If the element is present in the array print "1" else print "-1".Sample Input:
2
5 6
1 2 3 4 6
5 2
1 3 4 5 6
Sample Output:
1
-1, I have written this Solution Code: // arr is they array to search from
// x is target
function binSearch(arr, x) {
// write code here
// do not console.log
// return the 1 or -1
let l = 0;
let r = arr.length - 1;
let mid;
while (r >= l) {
mid = l + Math.floor((r - l) / 2);
// If the element is present at the middle
// itself
if (arr[mid] == x)
return 1;
// If element is smaller than mid, then
// it can only be present in left subarray
if (arr[mid] > x)
r = mid - 1;
// Else the element can only be present
// in right subarray
else
l = mid + 1;
}
// We reach here when element is not
// present in array
return -1;
}, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given the following pseudocode:
code :
res = a
for i = 1 to k
if i is odd
res = res & b
else
res = res | b
You are also given the values of a, b and k. Find the value of res.First line contains of single integer t denoting number of test cases.
Each test cases consists of 3 lines where each line consists of a single integer denoting the values of a, b and k respectively.
<b>Constraints</b>
1<= T <= 1e5
1<= a, b, k <= 1e18Print the final value of res for each test case in a new lineSample Input :
1
4 5 1
Sample Output :
4, I have written this Solution Code: def solve(a,b,k):
res=a
for i in range(1,k):
if(i%2==1):
res= res & b
else:
res= res | b
return res
t=int(input())
for i in range(t):
a,b,k=list(map(int, input().split()))
if k==1:
print(a&b)
else:
print(b), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given the following pseudocode:
code :
res = a
for i = 1 to k
if i is odd
res = res & b
else
res = res | b
You are also given the values of a, b and k. Find the value of res.First line contains of single integer t denoting number of test cases.
Each test cases consists of 3 lines where each line consists of a single integer denoting the values of a, b and k respectively.
<b>Constraints</b>
1<= T <= 1e5
1<= a, b, k <= 1e18Print the final value of res for each test case in a new lineSample Input :
1
4 5 1
Sample Output :
4, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int tt;
cin >> tt;
while (tt--) {
int a, b, k;
cin >> a >> b >> k;
cout << ((k == 1) ? a & b : b) << "\n";
}
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given the following pseudocode:
code :
res = a
for i = 1 to k
if i is odd
res = res & b
else
res = res | b
You are also given the values of a, b and k. Find the value of res.First line contains of single integer t denoting number of test cases.
Each test cases consists of 3 lines where each line consists of a single integer denoting the values of a, b and k respectively.
<b>Constraints</b>
1<= T <= 1e5
1<= a, b, k <= 1e18Print the final value of res for each test case in a new lineSample Input :
1
4 5 1
Sample Output :
4, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
for(int j=0;j<t;j++){
String[] arr = br.readLine().split(" ");
long a = Long.parseLong(arr[0]);
long b = Long.parseLong(arr[1]);
long k = Long.parseLong(arr[2]);
System.out.println((k==1)?a&b:b);
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a matrix of size N*N, your task is to find the sum of the primary and secondary diagonal of the matrix.
For Matrix:-
M<sub>00</sub> M<sub>01</sub> M<sub>02</sub>
M<sub>10</sub> M<sub>11</sub> M<sub>12</sub>
M<sub>20</sub> M<sub>21</sub> M<sub>22</sub>
Primary diagonal:- M<sub>00</sub> M<sub>11</sub> M<sub>22</sub>
Secondary diagonal:- M<sub>02</sub> M<sub>11</sub> M<sub>20</sub>The first line of input contains a single integer N, The next N lines of input contains N space-separated integers depicting the values of the matrix.
Constraints:-
1 <= N <= 500
1 <= Matrix[][] <= 100000Print the sum of primary and secondary diagonal separated by a space.Sample Input:-
2
1 4
2 6
Sample Output:-
7 6
Sample Input:-
3
1 4 2
1 5 7
3 8 1
Sample Output:-
7 10, I have written this Solution Code:
#include <bits/stdc++.h>
using namespace std;
#define MEM(a, b) memset(a, (b), sizeof(a))
#define FOREACH(it, l) for (auto it = l.begin(); it != l.end(); it++)
#define IN(A, B, C) assert( B <= A && A <= C)
#define MP make_pair
#define FOR(i,a) for(int i=0;i<a;i++)
#define FOR1(i,j,a) for(int i=j;i<a;i++)
#define EB emplace_back
#define INF (int)1e9
#define EPS 1e-9
#define PI 3.1415926535897932384626433832795
#define max1 1000001
#define MOD 1000000007
#define read(type) readInt<type>()
#define out(x) cout<<x<<'\n'
#define out1(x) cout<<x<<" "
#define END cout<<'\n'
#define int long long
#define sz(v) ((int)(v).size())
#define all(v) (v).begin(), (v).end()
void fast(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}
signed main(){
int n;
cin>>n;
int a[n][n];
FOR(i,n){
FOR(j,n){
cin>>a[i][j];}}
int sum=0,sum1=0;;
FOR(i,n){
sum+=a[i][i];
sum1+=a[n-i-1][i];
}
out1(sum);out(sum1);
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a matrix of size N*N, your task is to find the sum of the primary and secondary diagonal of the matrix.
For Matrix:-
M<sub>00</sub> M<sub>01</sub> M<sub>02</sub>
M<sub>10</sub> M<sub>11</sub> M<sub>12</sub>
M<sub>20</sub> M<sub>21</sub> M<sub>22</sub>
Primary diagonal:- M<sub>00</sub> M<sub>11</sub> M<sub>22</sub>
Secondary diagonal:- M<sub>02</sub> M<sub>11</sub> M<sub>20</sub>The first line of input contains a single integer N, The next N lines of input contains N space-separated integers depicting the values of the matrix.
Constraints:-
1 <= N <= 500
1 <= Matrix[][] <= 100000Print the sum of primary and secondary diagonal separated by a space.Sample Input:-
2
1 4
2 6
Sample Output:-
7 6
Sample Input:-
3
1 4 2
1 5 7
3 8 1
Sample Output:-
7 10, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String args[])throws Exception {
InputStreamReader inr= new InputStreamReader(System.in);
BufferedReader br= new BufferedReader(inr);
String str=br.readLine();
int row = Integer.parseInt(str);
int col=row;
int [][] arr=new int [row][col];
for(int i=0;i<row;i++){
String line =br.readLine();
String[] elements = line.split(" ");
for(int j=0;j<col;j++){
arr[i][j]= Integer.parseInt(elements[j]);
}
}
int sumPrimary=0;
int sumSecondary=0;
for(int i=0;i<row;i++){
sumPrimary=sumPrimary + arr[i][i];
sumSecondary= sumSecondary + arr[i][row-1-i];
}
System.out.println(sumPrimary+ " " +sumSecondary);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a matrix of size N*N, your task is to find the sum of the primary and secondary diagonal of the matrix.
For Matrix:-
M<sub>00</sub> M<sub>01</sub> M<sub>02</sub>
M<sub>10</sub> M<sub>11</sub> M<sub>12</sub>
M<sub>20</sub> M<sub>21</sub> M<sub>22</sub>
Primary diagonal:- M<sub>00</sub> M<sub>11</sub> M<sub>22</sub>
Secondary diagonal:- M<sub>02</sub> M<sub>11</sub> M<sub>20</sub>The first line of input contains a single integer N, The next N lines of input contains N space-separated integers depicting the values of the matrix.
Constraints:-
1 <= N <= 500
1 <= Matrix[][] <= 100000Print the sum of primary and secondary diagonal separated by a space.Sample Input:-
2
1 4
2 6
Sample Output:-
7 6
Sample Input:-
3
1 4 2
1 5 7
3 8 1
Sample Output:-
7 10, I have written this Solution Code: // mat is the matrix/ 2d array
// the dimensions of array are n * n
function diagonalSum(mat, n) {
// write code here
// console.log the answer as in example
let principal = 0, secondary = 0;
for (let i = 0; i < n; i++) {
principal += mat[i][i];
secondary += mat[i][n - i - 1];
}
console.log(`${principal} ${secondary}`);
}
, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a matrix of size N*N, your task is to find the sum of the primary and secondary diagonal of the matrix.
For Matrix:-
M<sub>00</sub> M<sub>01</sub> M<sub>02</sub>
M<sub>10</sub> M<sub>11</sub> M<sub>12</sub>
M<sub>20</sub> M<sub>21</sub> M<sub>22</sub>
Primary diagonal:- M<sub>00</sub> M<sub>11</sub> M<sub>22</sub>
Secondary diagonal:- M<sub>02</sub> M<sub>11</sub> M<sub>20</sub>The first line of input contains a single integer N, The next N lines of input contains N space-separated integers depicting the values of the matrix.
Constraints:-
1 <= N <= 500
1 <= Matrix[][] <= 100000Print the sum of primary and secondary diagonal separated by a space.Sample Input:-
2
1 4
2 6
Sample Output:-
7 6
Sample Input:-
3
1 4 2
1 5 7
3 8 1
Sample Output:-
7 10, I have written this Solution Code: n = int(input())
sum1 = 0
sum2 = 0
for i in range(n):
a = [int(j) for j in input().split()]
sum1 = sum1+a[i]
sum2 = sum2+a[n-1-i]
print(sum1,sum2), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Remove duplicates of an array and return an array of only unique elements.An array containing numbers.Space separated unique elements from the array.Sample Input:-
1 2 3 5 1 5 9 1 2 8
Sample Output:-
1 2 3 5 9 8
<b>Explanation:-</b>
Extra 1, 2, and 5 were removed since they were occurring multiple times.
Note: You only have to remove the extra occurrences i.e. each element in the final array should have a frequency equal to one., I have written this Solution Code: nan, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Remove duplicates of an array and return an array of only unique elements.An array containing numbers.Space separated unique elements from the array.Sample Input:-
1 2 3 5 1 5 9 1 2 8
Sample Output:-
1 2 3 5 9 8
<b>Explanation:-</b>
Extra 1, 2, and 5 were removed since they were occurring multiple times.
Note: You only have to remove the extra occurrences i.e. each element in the final array should have a frequency equal to one., I have written this Solution Code:
inp = eval(input(""))
new_set = []
for i in inp:
if(str(i) not in new_set):
new_set.append(str(i))
print(" ".join(new_set)), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Sara selects two different numbers from the range 1 to 50 and noted their sum as N. However later she Forgets which numbers she selected and now wants to know the total number of possible combinations she can have.<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>forgottenNumbers()</b> that takes integer N argument.
Constraints:-
3 <= N <= 99Return the total number of choices Sara has.Sample Input:-
8
Sample Output:-
3
Explanation:-
(1, 7), (2, 6), (3, 5)
Sample Input:-
3
Sample Output:-
1, I have written this Solution Code: int forgottenNumbers(int N){
int ans=0;
for(int i=1;i<=50;i++){
for(int j=1;j<=50;j++){
if(i!=j && i+j==N){
ans++;
}
}
}
return ans/2;
}
, In this Programming Language: C, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Sara selects two different numbers from the range 1 to 50 and noted their sum as N. However later she Forgets which numbers she selected and now wants to know the total number of possible combinations she can have.<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>forgottenNumbers()</b> that takes integer N argument.
Constraints:-
3 <= N <= 99Return the total number of choices Sara has.Sample Input:-
8
Sample Output:-
3
Explanation:-
(1, 7), (2, 6), (3, 5)
Sample Input:-
3
Sample Output:-
1, I have written this Solution Code: static int forgottenNumbers(int N){
int ans=0;
for(int i=1;i<=50;i++){
for(int j=1;j<=50;j++){
if(i!=j && i+j==N){
ans++;
}
}
}
return ans/2;
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Sara selects two different numbers from the range 1 to 50 and noted their sum as N. However later she Forgets which numbers she selected and now wants to know the total number of possible combinations she can have.<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>forgottenNumbers()</b> that takes integer N argument.
Constraints:-
3 <= N <= 99Return the total number of choices Sara has.Sample Input:-
8
Sample Output:-
3
Explanation:-
(1, 7), (2, 6), (3, 5)
Sample Input:-
3
Sample Output:-
1, I have written this Solution Code: int forgottenNumbers(int N){
int ans=0;
for(int i=1;i<=50;i++){
for(int j=1;j<=50;j++){
if(i!=j && i+j==N){
ans++;
}
}
}
return ans/2;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Sara selects two different numbers from the range 1 to 50 and noted their sum as N. However later she Forgets which numbers she selected and now wants to know the total number of possible combinations she can have.<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>forgottenNumbers()</b> that takes integer N argument.
Constraints:-
3 <= N <= 99Return the total number of choices Sara has.Sample Input:-
8
Sample Output:-
3
Explanation:-
(1, 7), (2, 6), (3, 5)
Sample Input:-
3
Sample Output:-
1, I have written this Solution Code: def forgottenNumbers(N):
ans = 0
for i in range (1,51):
for j in range (1,51):
if i != j and i+j==N:
ans=ans+1
return ans//2
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Sid is super fond of making couples, so he used to play FLAMES in his childhood.
Today, he is engrossed in a similar problem. There are N girls numbered from 1 to N, and N boys numbered from 1 to N. He wants to make exactly N couples from these group of young adults. He only has one criterion in mind:
-> The absolute value of the difference between the number assigned to the boy and the number assigned to the girl in any couple must not be equal to X.
He is a super loyal guy, so a boy and a girl can appear in at most 1 couple. You need to find the number of ways in which he can form these N couples. As the answer can be huge, you need to report it modulo 1000000007.
Since the problem is trickier than he expected, he is willing to give a Chapo to the person who solves it. Can you get a Chapo?The first and the only line of input contains two integers N and X.
Constraints
2 <= N <= 1500
1 <= X <= N-1Output a single integer, the answer to this colourful problem, modulo 1000000007.Sample Input
4 1
Sample Output
5
Explanation
The following ways of couple formation are valid:-
1. {(1, 1), (2, 2), (3, 3), (4, 4)}
2. {(1, 1), (4, 2), (3, 3), (2, 4)}
3. {(1, 3), (2, 2), (3, 1), (4, 4)}
4. {(1, 3), (2, 4), (3, 1), (4, 2)}
5. {(1, 4), (3, 3), (4, 1), (2, 2)}, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
#define sd(x) scanf("%d", &x)
#define sz(v) (int) v.size()
#define pr(v) For(i, 0, sz(v)) {cout<<v[i]<<" ";} cout<<endl;
#define slld(x) scanf("%lld", &x)
#define all(x) x.begin(), x.end()
#define For(i, st, en) for(ll i=st; i<en; i++)
#define tr(x) for(auto it=x.begin(); it!=x.end(); it++)
#define fast std::ios::sync_with_stdio(false);cin.tie(NULL);
#define pb push_back
#define ll long long
#define int long long
#define mp make_pair
#define F first
#define S second
typedef pair<int, int> pii;
typedef vector<int> vi;
#define MOD 1000000007
#define INF 1000000000000000007LL
const int N = 200005;
// it's swapnil07 ;)
#ifdef SWAPNIL07
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void __f(const char* name, Arg1&& arg1){
cout << name << " : " << arg1 << endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args){
const char* comma = strchr(names + 1, ',');cout.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...);
}
int begtime = clock();
#define end_routine() cout << "\n\nTime elapsed: " << (clock() - begtime)*1000/CLOCKS_PER_SEC << " ms\n\n";
#else
#define endl '\n'
#define trace(...)
#define end_routine()
#endif
int add(int a, int b){
return ((a + b) % MOD);
}
int mul(int a, int b){
return ((a * b) % MOD);
}
signed main()
{
fast
#ifdef SWAPNIL07
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n, k;
cin >> n >> k;
vector <int> a(n + 1);
a[0] = 1;
vector <int> used(n);
for (int i = 0; i < n; ++i)
{
if (used[i])
continue;
used[i] = 1;
vector <vector <int>> dp(n + 1, vector <int> (2)), ndp(n + 1, vector <int> (2));
int mxlen = 0;
dp[0][0] = 1;
if (i - k >= 0)
dp[1][0] = 1, mxlen = 1;
if (i + k < n)
dp[1][1] = 1, mxlen = 1;
for (int j = i + 2 * k; j < n; j += 2 * k){
used[j] = 1;
mxlen++;
for (int l = 0; l <= mxlen; ++l)
{
ndp[l][0] = add(dp[l][0], dp[l][1]);
if (l)
ndp[l][0] = add(ndp[l][0], dp[l - 1][0]);
if (l && j + k < n)
ndp[l][1] = add(dp[l - 1][0], dp[l - 1][1]);
}
swap(ndp, dp);
for (int l = 0; l <= mxlen; l++)
{
ndp[l][0] = ndp[l][1] = 0;
}
}
vector <int> na(n + 1);
for (int x = 0; x <= n; ++x)
for (int y = 0; y <= mxlen; ++y)
if (x + y <= n)
na[x + y] = add(na[x + y], mul(a[x], add(dp[y][0], dp[y][1])));
a = na;
}
vector <int> fact(n + 1, 1);
for (int i = 1; i <= n; ++i){
fact[i] = mul(fact[i - 1], i);
}
int ans = 0;
for (int i = 0; i <= n; i++){
// inclusion-exclusion
ans = add(ans, MOD + (i % 2 == 0 ? 1 : -1) * mul(a[i], fact[n - i]));
}
cout << ans;
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Arpit Gupta has brought a toy for his valentine. She is playing with that toy which runs for T seconds when winded.If winded when the toy is already running, from that moment it will run for T seconds (not additional T seconds) For example if T is 10 and toy has run for 5 seconds and winded at this moment then in total it will run for 15 seconds.
Arpit's Valentine winds the toy N times.She winds the toy at t[i] seconds after the first time she winds it.How long will the toy run in total?First Line of input contains two integers N and T
Second Line of input contains N integers, list of time Arpit's Valentine has wound the toy at.
Constraints
1 <= N <= 100000
1 <= T <= 1000000000
1 <= t[i] <= 1000000000
t[0] = 0Print a single integer the total time the toy has run.Sample input 1
2 4
0 3
Sample output 1
7
Sample input 2
2 10
0 5
Sample output 2
15
Explanation:
Testcase1:-
at first the toy is winded at 0 it will go till 4 but it again winded at 3 making it go for more 4 seconds
so the total is 7, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args)throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String[] str=br.readLine().split(" ");
int n=Integer.parseInt(str[0]);
int t=Integer.parseInt(str[1]);
int[] arr=new int[n];
str=br.readLine().split(" ");
for(int i=0;i<n;i++){
arr[i]=Integer.parseInt(str[i]);
}
int sum=0;
for(int i=1;i<n;i++){
int dif=arr[i]-arr[i-1];
if(dif>t){
sum=sum+t;
}else{
sum=sum+dif;
}
}
sum+=t;
System.out.print(sum);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Arpit Gupta has brought a toy for his valentine. She is playing with that toy which runs for T seconds when winded.If winded when the toy is already running, from that moment it will run for T seconds (not additional T seconds) For example if T is 10 and toy has run for 5 seconds and winded at this moment then in total it will run for 15 seconds.
Arpit's Valentine winds the toy N times.She winds the toy at t[i] seconds after the first time she winds it.How long will the toy run in total?First Line of input contains two integers N and T
Second Line of input contains N integers, list of time Arpit's Valentine has wound the toy at.
Constraints
1 <= N <= 100000
1 <= T <= 1000000000
1 <= t[i] <= 1000000000
t[0] = 0Print a single integer the total time the toy has run.Sample input 1
2 4
0 3
Sample output 1
7
Sample input 2
2 10
0 5
Sample output 2
15
Explanation:
Testcase1:-
at first the toy is winded at 0 it will go till 4 but it again winded at 3 making it go for more 4 seconds
so the total is 7, I have written this Solution Code: n , t = [int(x) for x in input().split() ]
l= [int(x) for x in input().split() ]
c = 0
for i in range(len(l)-1):
if l[i+1] - l[i]<=t:
c+=l[i+1] - l[i]
else:
c+=t
c+=t
print(c), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Arpit Gupta has brought a toy for his valentine. She is playing with that toy which runs for T seconds when winded.If winded when the toy is already running, from that moment it will run for T seconds (not additional T seconds) For example if T is 10 and toy has run for 5 seconds and winded at this moment then in total it will run for 15 seconds.
Arpit's Valentine winds the toy N times.She winds the toy at t[i] seconds after the first time she winds it.How long will the toy run in total?First Line of input contains two integers N and T
Second Line of input contains N integers, list of time Arpit's Valentine has wound the toy at.
Constraints
1 <= N <= 100000
1 <= T <= 1000000000
1 <= t[i] <= 1000000000
t[0] = 0Print a single integer the total time the toy has run.Sample input 1
2 4
0 3
Sample output 1
7
Sample input 2
2 10
0 5
Sample output 2
15
Explanation:
Testcase1:-
at first the toy is winded at 0 it will go till 4 but it again winded at 3 making it go for more 4 seconds
so the total is 7, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
int main(){
long n,t;
cin>>n>>t;
long a[n];
for(int i=0;i<n;i++){
cin>>a[i];
}
long cur=t;
long ans=t;
for(int i=1;i<n;i++){
ans+=min(a[i]-a[i-1],t);
}
cout<<ans;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a string S you have to remove all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, remove them as well. Repeat this untill no adjacent letter in the string is same.
Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result.The input data consists of a single string S.
Constraints:
1 <= |S| <= 100000
S contains lowercase english letters only.Print the given string after it is processed. It is guaranteed that the result will contain at least one character.Sample Input
hhoowaaaareyyoouu
Sample Output
wre
Explanation:
First we remove "hh" then "oo" then "aa" then "yy" then "oo" then "uu" and we are left with "wre".
Now we cannot remove anything.
Sample Input:-
abcde
Sample Output:-
abcde
Sample Input:-
abcddcb
Sample Output:-
a, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws IOException {
BufferedReader in =new BufferedReader(new InputStreamReader(System.in));
StringBuilder s = new StringBuilder();
String text=null;
while ((text = in.readLine ()) != null)
{
s.append(text);
}
int len=s.length();
for(int i=0;i<len-1;i++){
if(s.charAt(i)==s.charAt(i+1)){
int flag=0;
s.delete(i,i+2);
int left=i-1;
len=len-2;
i=i-2;
if(i<0){
i=-1;
}
}
}
System.out.println(s);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a string S you have to remove all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, remove them as well. Repeat this untill no adjacent letter in the string is same.
Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result.The input data consists of a single string S.
Constraints:
1 <= |S| <= 100000
S contains lowercase english letters only.Print the given string after it is processed. It is guaranteed that the result will contain at least one character.Sample Input
hhoowaaaareyyoouu
Sample Output
wre
Explanation:
First we remove "hh" then "oo" then "aa" then "yy" then "oo" then "uu" and we are left with "wre".
Now we cannot remove anything.
Sample Input:-
abcde
Sample Output:-
abcde
Sample Input:-
abcddcb
Sample Output:-
a, I have written this Solution Code: s=input()
l=["aa","bb","cc","dd","ee","ff","gg","hh","ii","jj","kk","ll","mm","nn","oo","pp","qq","rr","ss","tt","uu","vv","ww","xx","yy","zz"]
while True:
do=False
for i in range(len(l)):
if l[i] in s:
do=True
while l[i] in s:
s=s.replace(l[i],"")
if do==False:
break
print(s), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a string S you have to remove all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, remove them as well. Repeat this untill no adjacent letter in the string is same.
Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result.The input data consists of a single string S.
Constraints:
1 <= |S| <= 100000
S contains lowercase english letters only.Print the given string after it is processed. It is guaranteed that the result will contain at least one character.Sample Input
hhoowaaaareyyoouu
Sample Output
wre
Explanation:
First we remove "hh" then "oo" then "aa" then "yy" then "oo" then "uu" and we are left with "wre".
Now we cannot remove anything.
Sample Input:-
abcde
Sample Output:-
abcde
Sample Input:-
abcddcb
Sample Output:-
a, I have written this Solution Code: #pragma GCC optimize ("Ofast")
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define VV vector
#define pb push_back
#define bitc __builtin_popcountll
#define m_p make_pair
#define infi 1e18+1
#define eps 0.000000000001
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);
string char_to_str(char c){string tem(1,c);return tem;}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<class T>//usage rand<long long>()
T rand() {
return uniform_int_distribution<T>()(rng);
}
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template<class T>
using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
// string to integer stoi()
// string to long long stoll()
// string.substr(position,length);
// integer to string to_string();
//////////////
auto clk=clock();
#define all(x) x.begin(),x.end()
#define S second
#define F first
#define sz(x) ((long long)x.size())
#define int long long
#define f80 __float128
#define pii pair<int,int>
/////////////
signed main(){
fastio;
#ifdef ANIKET_GOYAL
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
string s;
cin>>s;
int len=s.length();
char stk[410000];
int k = 0;
for (int i = 0; i < len; i++)
{
stk[k++] = s[i];
while (k > 1 && stk[k - 1] == stk[k - 2])
k -= 2;
}
for (int i = 0; i < k; i++)
cout << stk[i];
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Negi is fascinated with the binary representation of the number. Tell him the number of set bits (ones) in the binary representation of an integer N.The first line of the input contains single integer N.
Constraints
1 <= N <= 1000000000000The output should contain a single integer, the number of set bits (ones) in the binary representation of an integer N.Sample Input
7
Sample Output
3
Sample Input
16
Sample Output
1, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args)throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
long n = Long.parseLong(br.readLine());
int count = 0;
try{
while (n > 0) {
count += n & 1;
n >>= 1;
}
}catch(Exception e){
return ;
}
System.out.println(count);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Negi is fascinated with the binary representation of the number. Tell him the number of set bits (ones) in the binary representation of an integer N.The first line of the input contains single integer N.
Constraints
1 <= N <= 1000000000000The output should contain a single integer, the number of set bits (ones) in the binary representation of an integer N.Sample Input
7
Sample Output
3
Sample Input
16
Sample Output
1, I have written this Solution Code: a=int(input())
l=bin(a)
print(l.count('1')), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Negi is fascinated with the binary representation of the number. Tell him the number of set bits (ones) in the binary representation of an integer N.The first line of the input contains single integer N.
Constraints
1 <= N <= 1000000000000The output should contain a single integer, the number of set bits (ones) in the binary representation of an integer N.Sample Input
7
Sample Output
3
Sample Input
16
Sample Output
1, I have written this Solution Code: #include<bits/stdc++.h>
using namespace std;
#define pu push_back
#define fi first
#define se second
#define mp make_pair
#define int long long
#define pii pair<int,int>
#define mm (s+e)/2
#define all(x) x.begin(), x.end()
#define For(i, st, en) for(int i=st; i<en; i++)
#define tr(x) for(auto it=x.begin(); it!=x.end(); it++)
#define fast std::ios::sync_with_stdio(false);cin.tie(NULL);
#define sz 200000
#define qw1 freopen("input1.txt", "r", stdin); freopen("output1.txt", "w", stdout);
#define qw2 freopen("input2.txt", "r", stdin); freopen("output2.txt", "w", stdout);
#define qw3 freopen("input3.txt", "r", stdin); freopen("output3.txt", "w", stdout);
#define qw4 freopen("input4.txt", "r", stdin); freopen("output4.txt", "w", stdout);
#define qw5 freopen("input5.txt", "r", stdin); freopen("output5.txt", "w", stdout);
#define qw6 freopen("input6.txt", "r", stdin); freopen("output6.txt", "w", stdout);
#define qw freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
signed main()
{
int n;
cin>>n;
int cnt=0;
while(n>0)
{
int p=n%2LL;
cnt+=p;
n/=2LL;
}
cout<<cnt<<endl;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: There is a function F defined as,
F(x) = GCD(1, x) + GCD(2, x) +. . + GCD(x, x)
Your task is to find F(x), for the given x.First line contain integer T denoting number of test cases.
Next t lines contain an integer x.
Constraints
1 <= T <= 20000
1 <= x <= 100000For each test case print F(n) in separate lineSample Input
5
1
2
3
4
5
Sample output
1
3
5
8
9, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
static int getCount(int no)
{
int result = no;
for(int p = 2; p * p <= no; ++p)
{
if (no % p == 0)
{
while (no % p == 0)
no /= p;
result -= result / p;
}
}
if (no > 1)
result -= result / no;
return result;
}
static int sumOfGCDofPairs(int n)
{
int res = 0;
for(int i = 1; i * i <= n; i++)
{
if (n % i == 0)
{
int d1 = i;
int d2 = n / i;
res += d1 * getCount(n/d1);
if (d1 != d2)
res += d2 * getCount(n/d2);
}
}
return res;
}
public static void main (String[] args) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine().trim());
for(int T=0;T<t;T++)
{
int x=Integer.parseInt(br.readLine().trim());
System.out.println(sumOfGCDofPairs(x));
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: There is a function F defined as,
F(x) = GCD(1, x) + GCD(2, x) +. . + GCD(x, x)
Your task is to find F(x), for the given x.First line contain integer T denoting number of test cases.
Next t lines contain an integer x.
Constraints
1 <= T <= 20000
1 <= x <= 100000For each test case print F(n) in separate lineSample Input
5
1
2
3
4
5
Sample output
1
3
5
8
9, I have written this Solution Code: def getCount(d,n):
no = n // d
result = no
p=2
while(p * p <= no):
if(no % p == 0):
while(no % p == 0):
no = no // p
result = result - (result // p)
p += 1
if(no > 1):
result = result - (result // no)
return result
def getSumOfGCDOfPairs(n):
result = 0
i =1
while(i * i <= n):
if(n % i == 0):
d1 = i
d2 = n // i
result = result + (d1 * getCount(d1, n))
if(d1 != d2):
result = result + (d2 * getCount(d2, n))
i += 1
return result
k = int(input())
for i in range(k):
n = int(input())
sum1 = 0
sum1 = getSumOfGCDOfPairs(n)
print(sum1), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: There is a function F defined as,
F(x) = GCD(1, x) + GCD(2, x) +. . + GCD(x, x)
Your task is to find F(x), for the given x.First line contain integer T denoting number of test cases.
Next t lines contain an integer x.
Constraints
1 <= T <= 20000
1 <= x <= 100000For each test case print F(n) in separate lineSample Input
5
1
2
3
4
5
Sample output
1
3
5
8
9, I have written this Solution Code: #include<iostream>
#include<string>
#include<vector>
#include<bitset>
#include<algorithm>
#include<cmath>
#include<set>
#include<climits>
using namespace std;
#define mod 1000000007
#define MAX 100000
void fast(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
}
vector < int > phi(MAX+1);
vector <long long > result(MAX+1);
void euler_totient(){
for(int i = 1 ; i <= MAX ; i++) phi[i] = i;
for(long long i = 2 ; i <= MAX ; i++){
if(phi[i] == i){
for(long long j = i ; j <= MAX ; j += i){
phi[j]/=i;
phi[j]*=(i-1);
}
}
}
}
void precalc(){
for(int i = 1 ; i <= MAX ; i++){
result[i] = i ;
}
for(int i = 1 ; i <= MAX ; i++){
for(int j = 2 ; j*i <= MAX ; j++){
result[i*j] += i*phi[j];
}
}
}
int main(){
fast();
euler_totient();
precalc();
int t;cin>>t;
while(t--){
int n;cin>>n;
cout<<result[n]<<"\n";
}
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Andrew is now bored with usual prime numbers and decides to find prime numbers which has exactly three factors. He sits back and keeps on thinking random numbers, and asks you to tell him if the number he has chosen had exactly 3 factors. Now he has given <b>N</b> random numbers, you need to tell him "<b>Yes</b>" if those numbers had exactly 3 factors otherwise "<b>No</b>".
<b>Note:</b> You can consider the number to be factor of its own.First-line contains N, the number of random numbers he thinks of. Second-line contains the N numbers separated by space.
<b>Constraints:</b>
1 <= N <= 10^5
1 <= numbers <= 10^12Print N lines containing "Yes" or "No".Sample Input 1
3
2 4 6
Sample Output 1
No
Yes
No
Explanation:
2 has 2 factors: 1, 2
4 has 3 factors: 1,2,4
6 has 4 factors: 1,2,3,6
Sample Input 2
3
3 5 7
Sample Output 2
No
No
No, I have written this Solution Code: from math import sqrt
def isPrime(n):
if (n <= 1):
return False
if (n <= 3):
return True
if (n % 2 == 0 or n % 3 == 0):
return False
k= int(sqrt(n))+1
for i in range(5,k,6):
if (n % i == 0 or n % (i + 2) == 0):
return False
return True
def isThreeDisctFactors(n):
sq = int(sqrt(n))
if (1 * sq * sq != n):
return False
if (isPrime(sq)):
return True
else:
return False
N = int(input())
numbers = input().split()
for x in numbers:
if isThreeDisctFactors(int(x)):
print("Yes")
else:
print("No"), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Andrew is now bored with usual prime numbers and decides to find prime numbers which has exactly three factors. He sits back and keeps on thinking random numbers, and asks you to tell him if the number he has chosen had exactly 3 factors. Now he has given <b>N</b> random numbers, you need to tell him "<b>Yes</b>" if those numbers had exactly 3 factors otherwise "<b>No</b>".
<b>Note:</b> You can consider the number to be factor of its own.First-line contains N, the number of random numbers he thinks of. Second-line contains the N numbers separated by space.
<b>Constraints:</b>
1 <= N <= 10^5
1 <= numbers <= 10^12Print N lines containing "Yes" or "No".Sample Input 1
3
2 4 6
Sample Output 1
No
Yes
No
Explanation:
2 has 2 factors: 1, 2
4 has 3 factors: 1,2,4
6 has 4 factors: 1,2,3,6
Sample Input 2
3
3 5 7
Sample Output 2
No
No
No, I have written this Solution Code: import java.util.*;
import java.io.*;
import java.lang.*;
class Main
{
static int MAX = 1000005;
static long spf[] = new long[MAX+5];
public static void main (String[] args)throws IOException {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(read.readLine());
SOF();
String str[] = read.readLine().trim().split(" ");
for(int i = 0; i < N; i++)
{
long x = Long.parseLong(str[i]);
long g = (long)Math.sqrt(x);
if((g*g)!=x)
{
System.out.println("No");
}
else
{
if(spf[(int)g]==g)
{
System.out.println("Yes");
}
else
System.out.println("No");
}
}
}
public static void SOF()
{
spf[1] = 0;
for (int i=2; i<MAX; i++)
// marking smallest prime factor for every
// number to be itself.
spf[i] = i;
// separately marking spf for every even
// number as 2
for (int i=4; i<MAX; i+=2)
spf[i] = 2;
for (int i=3; i*i<MAX; i++)
{
// checking if i is prime
if (spf[i] == i)
{
// marking SPF for all numbers divisitedible by i
for (int j=i*i; j<MAX; j+=i)
// marking spf[j] if it is not
// previously marked
if (spf[j]==j)
spf[j] = i;
}
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Andrew is now bored with usual prime numbers and decides to find prime numbers which has exactly three factors. He sits back and keeps on thinking random numbers, and asks you to tell him if the number he has chosen had exactly 3 factors. Now he has given <b>N</b> random numbers, you need to tell him "<b>Yes</b>" if those numbers had exactly 3 factors otherwise "<b>No</b>".
<b>Note:</b> You can consider the number to be factor of its own.First-line contains N, the number of random numbers he thinks of. Second-line contains the N numbers separated by space.
<b>Constraints:</b>
1 <= N <= 10^5
1 <= numbers <= 10^12Print N lines containing "Yes" or "No".Sample Input 1
3
2 4 6
Sample Output 1
No
Yes
No
Explanation:
2 has 2 factors: 1, 2
4 has 3 factors: 1,2,4
6 has 4 factors: 1,2,3,6
Sample Input 2
3
3 5 7
Sample Output 2
No
No
No, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
#define max1 1000001
bool a[max1];
signed main()
{
string s="abcdefghijklmnopqrstuvwxyz";
for(int i=0;i<=1000000;i++){
a[i]=false;
}
for(int i=2;i<1000000;i++){
if(a[i]==false){
for(int j=i+i;j<=1000000;j+=i){
a[j]=true;
}
}
}
int n;
cin>>n;
long long x;
long long y;
for(int i=0;i<n;i++){
cin>>x;
long long y=sqrt(x);
if(y*y==x){
if(a[y]==false){cout<<"Yes"<<endl;}
else{cout<<"No"<<endl;}
}
else{
cout<<"No"<<endl;
}
}}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given 3 non-negative integers A, B and C. In one operation, you can pick any two of the given integers and subtract one from both of them.
If it is possible to make all the 3 integers zero after some number of operations (possibly none), print "Yes". Otherwise, print "No".The first line contains a single integer T – the number of test cases.
Each of the next T lines contains 3 space separated integers A, B and C respectively.
<b> Constraints: </b>
1 ≤ T ≤ 10
0 ≤ A, B, C ≤ 10Output T lines, the i<sup>th</sup> line containing a single word, either "Yes" or "No" – the answer to the i<sup>th</sup> test case.Sample Input 1:
2
3 4 2
2 2 2
Sample Output 1:
No
Yes
Sample Explanation 1:
For the first test case, there is no possible way to make all the elements zero.
For the second test case, we can pick elements in the following order: (A,B), (B,C), (A,C), I have written this Solution Code: import java.util.*;
import java.lang.*;
import java.io.*;
class Main {
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br=new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while(st==null || !st.hasMoreTokens()){
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
String nextLine(){
String str="";
try {
str=br.readLine().trim();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
static class FastWriter {
private final BufferedWriter bw;
public FastWriter() {
this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
public void print(Object object) throws IOException {
bw.append("").append(String.valueOf(object));
}
public void println(Object object) throws IOException {
print(object);
bw.append("\n");
}
public void close() throws IOException {
bw.close();
}
}
public static void main(String[] args) throws Exception{
try {
FastReader in=new FastReader();
FastWriter out = new FastWriter();
int testCases=in.nextInt();
while(testCases-- > 0) {
int a = in.nextInt(), b = in.nextInt(), c = in.nextInt();
while ((a>0&&b>0)||(a>0&&c>0)||(b>0&&c>0)) {
if (a >= b && a >= c) {
a--;
if (b >= c) {
b--;
}
else{
c--;
}
}
else if (b >= a && b >= c) {
b--;
if (a >= c) {
a--;
}
else{
c--;
}
}
else{
c--;
if (a >= b) {
a--;
}
else{
b--;
}
}
}
if (a==0&&b==0&&c==0){
out.println("Yes");
}
else{
out.println("No");
}
}
out.close();
} catch (Exception e) {
return;
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given 3 non-negative integers A, B and C. In one operation, you can pick any two of the given integers and subtract one from both of them.
If it is possible to make all the 3 integers zero after some number of operations (possibly none), print "Yes". Otherwise, print "No".The first line contains a single integer T – the number of test cases.
Each of the next T lines contains 3 space separated integers A, B and C respectively.
<b> Constraints: </b>
1 ≤ T ≤ 10
0 ≤ A, B, C ≤ 10Output T lines, the i<sup>th</sup> line containing a single word, either "Yes" or "No" – the answer to the i<sup>th</sup> test case.Sample Input 1:
2
3 4 2
2 2 2
Sample Output 1:
No
Yes
Sample Explanation 1:
For the first test case, there is no possible way to make all the elements zero.
For the second test case, we can pick elements in the following order: (A,B), (B,C), (A,C), I have written this Solution Code: t=int(input())
for i in range(t):
arr=list(map(int,input().split()))
a,b,c=sorted(arr)
if((a+b+c)%2):
print("No")
elif ((a+b)>=c):
print("Yes")
else:
print("No"), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given 3 non-negative integers A, B and C. In one operation, you can pick any two of the given integers and subtract one from both of them.
If it is possible to make all the 3 integers zero after some number of operations (possibly none), print "Yes". Otherwise, print "No".The first line contains a single integer T – the number of test cases.
Each of the next T lines contains 3 space separated integers A, B and C respectively.
<b> Constraints: </b>
1 ≤ T ≤ 10
0 ≤ A, B, C ≤ 10Output T lines, the i<sup>th</sup> line containing a single word, either "Yes" or "No" – the answer to the i<sup>th</sup> test case.Sample Input 1:
2
3 4 2
2 2 2
Sample Output 1:
No
Yes
Sample Explanation 1:
For the first test case, there is no possible way to make all the elements zero.
For the second test case, we can pick elements in the following order: (A,B), (B,C), (A,C), I have written this Solution Code:
// #pragma GCC optimize("Ofast")
// #pragma GCC target("avx,avx2,fma")
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
#define pi 3.141592653589793238
#define int long long
#define ll long long
#define ld long double
using namespace __gnu_pbds;
using namespace std;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());
long long powm(long long a, long long b,long long mod) {
long long res = 1;
while (b > 0) {
if (b & 1)
res = res * a %mod;
a = a * a %mod;
b >>= 1;
}
return res;
}
ll gcd(ll a, ll b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(0);
#ifndef ONLINE_JUDGE
if(fopen("input.txt","r"))
{
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
}
#endif
int t;
cin>>t;
while(t--)
{
int a,b,c;
cin>>a>>b>>c;
if(a>b+c||b>a+c||c>a+b)
cout<<"No\n";
else
{
int sum=a+b+c;
if(sum%2)
cout<<"No\n";
else
cout<<"Yes\n";
}
}
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Newton is given a grid A of N rows and M columns consisting of 2 colors, red and blue.
He is not very fond of the color red so he wants to remove all the rows and columns that contain only red color cells.
Print the final matrix that Newton is left with after removing all red rows and red columns.
(Note: The given matrix is of N rows and M columns. The cell at i-th row and j-th column, A<sub>i, j</sub> , contains a '. ' if it contains red color otherwise a '#' if it contains the color blue. )The first line of the input contains two integers N and M
Each of the next N lines contains a string of M characters representing the grid A.
<b>Constraints:</b>
1 ≤ N, M ≤ 100
A<sub>i, j</sub> is either '. ' or '#'Output the resultant grid<b>Sample Input 1:</b>
5 5
##. #.
. .
##. #.
. #. #.
#..
<b>Sample Output 1:</b>
###
###
. ##
#..
<b>Explanation:</b>
The second row, third column and fifth column will be removed
<b>Sample Input 2:</b>
4 4
. .
. .
. #.
. .
<b>Sample Output 2:</b>
#, I have written this Solution Code: // #pragma GCC optimize("Ofast")
// #pragma GCC target("avx,avx2,fma")
#pragma GCC optimize("O3")
#pragma GCC target("avx,avx2,sse,sse2,sse3,sse4,popcnt,fma")
#pragma GCC optimize("unroll-loops")
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define pb push_back
#define eb emplace_back
#define ff first
#define ss second
#define endl "\n"
#define EPS 1e-9
#define MOD 1000000007
#define yes cout<<"YES"<<endl;
#define no cout<<"NO"<<endl;
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define sz(x) (x).size()
// #define forf(t,i,n) for(t i=0;i<n;i++)
// #define forr(t,i,n) for(t i=n-1;i>=0;i--)
#define forf(i,a,b) for(ll i=a;i<b;i++)
#define forr(i,a,b) for(ll i=a;i>=b;i--)
#define F0(i, n) for(ll i=0; i<n; i++)
#define F1(i, n) for(ll i=1; i<=n; i++)
#define FOR(i, s, e) for(ll i=s; i<=e; i++)
#define ceach(a,x) for(const auto &a: x)
#define each(a,x) for(auto &a: x)
#define print(x) for(const auto &e: (x)) { cout<<e<<" "; } cout<<endl
#define daalo(a) each(x, a) { cin>>x; }
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair<int, int> pi;
typedef pair<long long, long long> pll;
typedef vector<int> vi;
typedef vector<long> vl;
typedef vector<long long> vll;
typedef vector<char> vc;
typedef vector<string> vs;
typedef vector<vector<int>> vvi;
typedef vector<vector<long long>> vvll;
typedef vector<vector<char>> vvc;
typedef vector<vector<string>> vvs;
typedef unordered_map<int, int> umi;
typedef unordered_map<long long, long long> umll;
typedef unordered_map<char, int> umci;
typedef unordered_map<char, long long> umcll;
typedef unordered_map<string, int> umsi;
typedef unordered_map<string, long long> umsll;
#ifndef ONLINE_JUDGE
#define deb(x ...) cerr << #x << ": "; _print(x); cerr << endl;
#define pt(x) cerr << "\n---------Testcase " << x << "---------\n" << endl;
// #define deb(x ...) ;
// #define pt(x) ;
#else
#define deb(x ...) ;
#define pt(x) ;
#endif
void _print(unsigned short t){ cerr << t; }
void _print(short t){ cerr << t; }
void _print(unsigned int t){ cerr << t; }
void _print(int t){ cerr << t; }
void _print(unsigned long t){ cerr << t; }
void _print(long t){ cerr << t; }
void _print(unsigned long long t){ cerr << t; }
void _print(long long t){ cerr << t; }
void _print(float t){ cerr << t; }
void _print(double t){ cerr << t; }
void _print(long double t){ cerr << t; }
void _print(unsigned char t){ cerr << t; }
void _print(char t){ cerr << t; }
void _print(string t){ cerr << t; }
template<typename A> void _print(vector<A> v);
template<typename A, typename B> void _print(pair<A, B> p);
template<typename A> void _print(set<A> s);
template<typename A, typename B> void _print(map<A, B> mp);
template<typename A> void _print(multiset<A> s);
template<typename A, typename B> void _print(multimap<A, B> mp);
template<typename A> void _print(unordered_set<A> s);
template<typename A, typename B> void _print(unordered_map<A, B> mp);
template<typename A> void _print(unordered_multiset<A> s);
template<typename A, typename B> void _print(unordered_multimap<A, B> mp);
template<typename A> void _print(stack<A> s);
template<typename A> void _print(queue<A> q);
template<typename A> void _print(priority_queue<A> pq);
template<typename A> void _print(priority_queue<A, vector<A>, greater<A>> pq);
template<typename A> void _print(vector<A> v){ if(!v.empty()){ cerr << "["; for(auto it=v.begin(); it!=(v.end()-1); it++){ _print(*it); cerr <<","; } _print(*(v.end()-1)); cerr << "]"; } else{ cerr << "[]"; } }
template<typename A, typename B> void _print(pair<A, B> p){ cerr << "{"; _print(p.first); cerr << ","; _print(p.second); cerr << "}"; }
template<typename A> void _print(set<A> s){ if(!s.empty()){ cerr << "{"; for(auto it=s.begin(), lit=next(it); lit!=(s.end()); it++, lit++){ _print(*it); cerr <<","; } _print(*(s.rbegin())); cerr << "}"; } else{ cerr << "{}"; } }
template<typename A, typename B> void _print(map<A, B> mp){ if(!mp.empty()){ cerr << "["; for(auto it=mp.begin(), lit=next(it); lit!=(mp.end()); it++, lit++){ _print(*it); cerr <<","; } _print(*(mp.rbegin())); cerr << "]"; } else{ cerr << "[]"; } }
template<typename A> void _print(multiset<A> s){ if(!s.empty()){ cerr << "{"; for(auto it=s.begin(), lit=next(it); lit!=(s.end()); it++, lit++){ _print(*it); cerr <<","; } _print(*(s.rbegin())); cerr << "}"; } else{ cerr << "{}"; } }
template<typename A, typename B> void _print(multimap<A, B> mp){ if(!mp.empty()){ cerr << "["; for(auto it=mp.begin(), lit=next(it); lit!=(mp.end()); it++, lit++){ _print(*it); cerr <<","; } _print(*(mp.rbegin())); cerr << "]"; } else{ cerr << "[]"; } }
template<typename A> void _print(unordered_set<A> s){ if(!s.empty()){ cerr << "{"; auto it = s.begin(); for(auto lit=next(it); lit!=(s.end()); it++, lit++){ _print(*it); cerr <<","; } _print(*it); cerr << "}"; } else{ cerr << "{}"; } }
template<typename A, typename B> void _print(unordered_map<A, B> mp){ if(!mp.empty()){ cerr << "["; auto it = mp.begin(); for(auto lit=next(it); lit!=(mp.end()); it++, lit++){ _print(*it); cerr <<","; } _print(*it); cerr << "]"; } else{ cerr << "[]"; } }
template<typename A> void _print(unordered_multiset<A> s){ if(!s.empty()){ cerr << "{"; auto it=s.begin(); for(auto lit=next(it); lit!=(s.end()); it++, lit++){ _print(*it); cerr <<","; } _print(*it); cerr << "}"; } else{ cerr << "{}"; } }
template<typename A, typename B> void _print(unordered_multimap<A, B> mp){ if(!mp.empty()){ cerr << "["; auto it=mp.begin(); for(auto lit=next(it); lit!=(mp.end()); it++, lit++){ _print(*it); cerr <<","; } _print(*it); cerr << "]"; } else{ cerr << "[]"; } }
template<typename A> void _print(stack<A> s){ if(!s.empty()){ stack<A> t; cerr << "T["; while(s.size() != 1){ _print(s.top()); cerr << ","; t.push(s.top()); s.pop(); } _print(s.top()); cerr << "]B"; t.push(s.top()); s.pop(); while(!t.empty()){ s.push(t.top()); t.pop(); } } else{ cerr << "T[]B"; } }
template<typename A> void _print(queue<A> q){ if(!q.empty()){ queue<A> t; cerr << "F["; while(q.size() != 1){ _print(q.front()); cerr << ","; t.push(q.front()); q.pop(); } _print(q.front()); cerr << "]B"; t.push(q.front()); q.pop(); while(!t.empty()){ q.push(t.front()); t.pop(); } } else{ cerr << "F[]B"; } }
template<typename A> void _print(priority_queue<A> pq){ if(!pq.empty()){ queue<A> t; cerr << "T["; while(pq.size() != 1){ _print(pq.top()); cerr << ","; t.push(pq.top()); pq.pop(); } _print(pq.top()); cerr << "]B"; t.push(pq.top()); pq.pop(); while(!t.empty()){ pq.push(t.front()); t.pop(); } } else{ cerr << "F[]B"; } }
template<typename A> void _print(priority_queue<A, vector<A>, greater<A>> pq){ if(!pq.empty()){ queue<A> t; cerr << "T["; while(pq.size() != 1){ _print(pq.top()); cerr << ","; t.push(pq.top()); pq.pop(); } _print(pq.top()); cerr << "]B"; t.push(pq.top()); pq.pop(); while(!t.empty()){ pq.push(t.front()); t.pop(); } } else{ cerr << "F[]B"; } }
template<typename T, typename... V> void _print(T t, V... v) {_print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
template<typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template<typename T> using ordered_multiset = tree<T, null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>;
template<typename T> using ordered_set_dec = tree<T, null_type, greater<T>, rb_tree_tag, tree_order_statistics_node_update>;
template<typename T> using ordered_multiset_dec = tree<T, null_type, greater_equal<T>, rb_tree_tag, tree_order_statistics_node_update>;
ll mod_mul(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;}
ll gcd(ll a, ll b) {if (b > a) {return gcd(b, a);} if (b == 0) {return a;} return gcd(b, a % b);}
ll expo(ll a, ll b, ll mod) {ll res = 1; while (b > 0) {if (b & 1)res = mod_mul(res , a, mod); a = mod_mul(a , a ,mod); b = b >> 1;} return res;}
void extendgcd(ll a, ll b, ll*v) {if (b == 0) {v[0] = 1; v[1] = 0; v[2] = a; return ;} extendgcd(b, a % b, v); ll x = v[1]; v[1] = v[0] - v[1] * (a / b); v[0] = x; return;} //pass an arry of size1 3
ll mminv(ll a, ll b) {ll arr[3]; extendgcd(a, b, arr); return arr[0];} //for non prime b
ll mminvprime(ll a, ll b) {return expo(a, b - 2, b);}
bool revsort(ll a, ll b) {return a > b;}
void swap(int &x, int &y) {int temp = x; x = y; y = temp;}
ll combination(ll n, ll r, ll m, ll *fact, ll *ifact) {ll val1 = fact[n]; ll val2 = ifact[n - r]; ll val3 = ifact[r]; return (((val1 * val2) % m) * val3) % m;}
void google(int t) {cout << "Case #" << t << ": ";}
vector<ll> sieve(int n) {int*arr = new int[n + 1](); vector<ll> vect; for (int i = 2; i <= n; i++)if (arr[i] == 0) {vect.push_back(i); for (int j = 2 * i; j <= n; j += i)arr[j] = 1;} return vect;}
ll mod_add(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;}
ll mod_sub(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;}
ll mod_div(ll a, ll b, ll m) {a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m;} //only for prime m
ll phin(ll n) {ll number = n; if (n % 2 == 0) {number /= 2; while (n % 2 == 0) n /= 2;} for (ll i = 3; i <= sqrt(n); i += 2) {if (n % i == 0) {while (n % i == 0)n /= i; number = (number / i * (i - 1));}} if (n > 1)number = (number / n * (n - 1)) ; return number;} //O(sqrt(N))
template<typename T>
T gcd(T a, T b){
if(b == 0)
return a;
return(gcd<T>(b, a%b));
}
template<typename T>
T lcm(T a, T b){
return (a / gcd<T>(a, b)) * b;
}
template<typename T>
void swap_(T &a, T &b){
a = a^b;
b = b^a;
a = a^b;
}
template<typename T>
T modpow(T a, T b, T m){
if(b == 0){
return 1;
}
T c = modpow(a, b/2, m);
c = (c * c)%m;
if(b%2 == 1){
c = (c * a)%m;
}
return c;
}
template<typename T>
vector<T> makeUnique(vector<T> &vec){
vector<T> temp;
unordered_map<T, long long> mp;
for(const auto &e: vec){
if(mp[e]++ == 0){
temp.push_back(e);
}
}
return temp;
}
vector<long long> primeFactorization(long long n) {
vector<long long> factorization;
for (int d : {2, 3, 5}) {
while (n % d == 0) {
factorization.push_back(d);
n /= d;
}
}
static array<int, 8> increments = {4, 2, 4, 2, 4, 6, 2, 6};
int i = 0;
for (long long d = 7; d * d <= n; d += increments[i++]) {
while (n % d == 0) {
factorization.push_back(d);
n /= d;
}
if (i == 8)
i = 0;
}
if (n > 1)
factorization.push_back(n);
return factorization;
}
vector<long long> divisors(long long n) {
vector<long long> divisors;
for(long long i = 1; i * i <= n; i++){
if(n % i == 0){
divisors.push_back(i);
if(n/i != i){
divisors.push_back(n/i);
}
}
}
return divisors;
}
vector<bool> seive(long long n){
vector<bool> is_prime(n+1, true);
is_prime[0] = is_prime[1] = false;
for (long long i = 2; i * i <= n; i++) {
if (is_prime[i]) {
for (long long j = i * i; j <= n; j += i)
is_prime[j] = false;
}
}
return is_prime;
}
// ------------ Segment Tree --------------
void segBuild(ll ind, ll l, ll r, vll &arr, vll &segtree){
if(l == r){
segtree[ind] = arr[l];
return;
}
ll m = (l+r)/2;
segBuild(2*ind, l, m, arr, segtree);
segBuild(2*ind+1, m+1, r, arr, segtree);
segtree[ind] = segtree[ind*2]+segtree[ind*2+1];
}
ll segSum(ll ind, ll tl, ll tr, ll l, ll r, vll &segtree){
if(l > r || tr < l || tl > r){
return 0;
}
if(tl >= l && tr <= r){
return segtree[ind];
}
ll m = (tl+tr)/2;
ll left = segSum(2*ind, tl, m, l, r, segtree);
ll right = segSum(2*ind+1, m+1, tr, l, r, segtree);
return left+right;
}
void segUpdate(ll ind, ll l, ll r, ll ind_val, ll val, vll &segtree){
if(l == r){
segtree[ind] = val;
return;
}
ll m = (l+r)/2;
if(ind_val <= m){
segUpdate(2*ind, l, m, ind_val, val, segtree);
}
else{
segUpdate(2*ind+1, m+1, r, ind_val, val, segtree);
}
segtree[ind] = segtree[ind*2]+segtree[ind*2+1];
}
// -----------------------------------
template<typename T>
string bitRep(T num, T size){
if(size == 8) return bitset<8>(num).to_string();
if(size == 16) return bitset<16>(num).to_string();
if(size == 32) return bitset<32>(num).to_string();
if(size == 64) return bitset<64>(num).to_string();
}
/* ----------STRING AND INTEGER CONVERSIONS---------- */
// 1) number to string -> to_string(num)
// 2) string to int -> stoi(str)
// 3) string to long long -> stoll(str)
// 4) string to decimal -> stod(str)
// 5) string to long decimal -> stold(str)
/* ----------Decimal Precision---------- */
// cout<<fixed<<setprecision(n) -> to fix precision to n decimal places.
// cout<<setprecision(n) -> without fixing
/* ----------Policy Bases Data Structures---------- */
// pbds<ll> s; (almost same as set)
// s.find_by_order(i) 0<=i<n returns iterator to ith element (0 if i>=n)
// s.order_of_key(e) returns elements strictly less than the given element e (need not be present)
/* ------------------Binary Search------------------ */
// 1) Lower Bound -> returns iterator to the first element greater than or equal to the given element or returns end() if no such element exists
// 2) Upper Bound -> returns iterator to the first element greater than the given element or returns end() if no such element exists
/* --------------Builtin Bit Functions-------------- */
// 1) __builtin_clz(x) -> returns the number of zeros at the beginning in the bit representaton of x.
// 2) __builtin_ctz(x) -> returns the number of zeros at the end in the bit representaton of x.
// 3) __builtin_popcount(x) -> returns the number of ones in the bit representaton of x.
// 4) __builtin_parity(x) -> returns the parity of the number of ones in the bit representaton of x.
/* ----------------------- Bitset ----------------------- */
// 1) Must have a constant size of bitset (not variable)
// 2) bitset<size> set;
// 3) Indexing starts from right
// 4) bitset<size> set; bitset<size> set(20); bitset<size> set(string("110011"));
// 5) set.to_string() -> return string of the binary representation
void solve(){
ll h, w; cin>>h>>w;
vector<vector<char>> v(h, vector<char>(w));
each(r, v){
daalo(r);
}
auto first = [&](){
vector<vector<char>> t;
F0(i, h){
vector<char> tt;
bool found = false;
F0(j, w){
if(v[i][j] == '#') found = true;
tt.pb(v[i][j]);
}
if(found) t.pb(tt);
}
v = t;
};
auto second = [&](){
vector<vector<char>> t;
F0(j, w){
vector<char> tt;
bool found = false;
F0(i, v.size()){
if(v[i][j] == '#') found = true;
tt.pb(v[i][j]);
}
if(found) t.pb(tt);
}
v = t;
};
first();
deb(v)
second();
deb(v)
for(int j=0; j<v[0].size(); j++){
for(int i=0; i<v.size(); i++){
cout<<v[i][j];
}
cout<<endl;
}
}
int main(){
// cfh - ctrl+alt+b
// #ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// freopen("error.txt", "w", stderr);
// #endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
ll t=1;
// cin >> t;
for(ll i=1; i<=t; i++){
pt(i);
solve();
}
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Peter Parker is taking part in a competition where Mr Tony Stark has come to see Peter lift the cup. But Tony can't tell what position Peter is on since the school authorities didn't display a leaderboard. Help Tony Identify which rank is Peter on by seeing his victory status in different rounds. Points are awarded on solving every question based on the difficulty level of the question which are divided into subcategories. The player with the highest score is ranked number 1 on the leaderboard. Players who have equal scores receive the same ranking number, and the next player(s) receive the immediately following ranking number.The first line contains an integer n, the number of participants on the leaderboard. The next line contains n space- separated integers containing the leaderboard points in decreasing order in the competition. The next line contains an integer m, denoting the number of times Peter is attempting the question. The last line contains m space- separated integers containing Peter's score in each attempt in the competition.
<b>Constraints:-</b>
1 <= n <= 10<sup>5</sup>
1 <= m <= 10<sup>3</sup>
1 <= points, score <= 10<sup>7</sup>
Note:-
In the existing leaderboard, points are in descending order. Peter's points are in ascending order.Print m integers indicating Peter's rank in each competition.Sample Input:-
7
100 100 50 40 40 20 10
4
5 25 50 120
Sample Output:-
6
4
2
1, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String line1 = br.readLine();
String[] num1 = line1.trim().split("\\s+");
int[] arr1 = new int[n];
for(int i = 0; i < n; i++)
{
arr1[i] = Integer.parseInt(num1[i]);
}
int m = Integer.parseInt(br.readLine());
int[] arr2 = new int[m];
String line2 = br.readLine();
String[] num2 = line2.trim().split("\\s+");
for(int i = 0; i < m; i++)
{
arr2[i] = Integer.parseInt(num2[i]);
}
Stack<Integer> st = new Stack<>();
for(int i = 0; i < n; i++)
{
while(!st.isEmpty() && st.peek() == arr1[i])
st.pop();
st.push(arr1[i]);
}
for(int i = 0; i < m; i++)
{
while(!st.isEmpty() && st.peek() <= arr2[i])
st.pop();
System.out.println(st.size() + 1);
st.push(arr2[i]);
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Peter Parker is taking part in a competition where Mr Tony Stark has come to see Peter lift the cup. But Tony can't tell what position Peter is on since the school authorities didn't display a leaderboard. Help Tony Identify which rank is Peter on by seeing his victory status in different rounds. Points are awarded on solving every question based on the difficulty level of the question which are divided into subcategories. The player with the highest score is ranked number 1 on the leaderboard. Players who have equal scores receive the same ranking number, and the next player(s) receive the immediately following ranking number.The first line contains an integer n, the number of participants on the leaderboard. The next line contains n space- separated integers containing the leaderboard points in decreasing order in the competition. The next line contains an integer m, denoting the number of times Peter is attempting the question. The last line contains m space- separated integers containing Peter's score in each attempt in the competition.
<b>Constraints:-</b>
1 <= n <= 10<sup>5</sup>
1 <= m <= 10<sup>3</sup>
1 <= points, score <= 10<sup>7</sup>
Note:-
In the existing leaderboard, points are in descending order. Peter's points are in ascending order.Print m integers indicating Peter's rank in each competition.Sample Input:-
7
100 100 50 40 40 20 10
4
5 25 50 120
Sample Output:-
6
4
2
1, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
int main(){
// freopen("ou.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
unsigned long n, m, i, tmp;
cin>> n;
stack<unsigned long> scores;
for (i = 0; i< n; ++i) {
cin>>tmp;
if (scores.empty() || scores.top() != tmp) scores.push(tmp);
}
cin>> m;
for (i = 0; i< m; ++i) {
cin>>tmp;
while (!scores.empty() &&tmp>= scores.top()) scores.pop();
cout<< (scores.size() + 1) <<endl;
}
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array A of N positive integers. The task is to find a subsequence with maximum sum such that there should be no adjacent elements from the array in the subsequence.First line of input contains T, the number of test case.
First line of test case contains size of array N. Next line contains N space separated integers representing the elements of the array.
Constraints:
1 <= T <= 100
1 <= N <= 10^5
1 <= A[i] <= 10^6
<b>Sum of N over all testcases does not exceed 10^6</b>For each testcase, print the maximum sum of the subsequenceSample Input:-
2
3
1 2 3
3
1 20 3
Sample Output:-
4
20
Explanation:
Testcase 1: Elements 1 and 3 form a subsequence with maximum sum and no elements in the subsequence are adjacent in the array.
Testcase 2: Element 20 from the array forms a subsequence with maximum sum., I have written this Solution Code: import java.io.*;
import java.util.*;
public class Main {
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64];
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static long maxCoins(int coins[]) {
int n = coins.length;
long prev2 = 0;
long prev1 = coins[0];
for (int i = 1; i < n; i++) {
long inc = prev2 + coins[i];
long exc = prev1;
long ans = Math.max(inc, exc);
prev2=prev1;
prev1 = ans;
}
return prev1;
}
public static void main(String[] args) throws IOException {
Reader sc = new Reader();
int t = sc.nextInt();
while(t-->0){
int n = sc.nextInt();
int arr[] = new int[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
System.out.println(maxCoins(arr));
}
sc.close();
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array A of N positive integers. The task is to find a subsequence with maximum sum such that there should be no adjacent elements from the array in the subsequence.First line of input contains T, the number of test case.
First line of test case contains size of array N. Next line contains N space separated integers representing the elements of the array.
Constraints:
1 <= T <= 100
1 <= N <= 10^5
1 <= A[i] <= 10^6
<b>Sum of N over all testcases does not exceed 10^6</b>For each testcase, print the maximum sum of the subsequenceSample Input:-
2
3
1 2 3
3
1 20 3
Sample Output:-
4
20
Explanation:
Testcase 1: Elements 1 and 3 form a subsequence with maximum sum and no elements in the subsequence are adjacent in the array.
Testcase 2: Element 20 from the array forms a subsequence with maximum sum., I have written this Solution Code:
def rob(nums) -> int:
rob1, rob2 =0, 0
for n in nums:
temp = max(n + rob1, rob2)
rob1 = rob2
rob2 = temp
return rob2
t=int(input())
while t!=0:
t-=1
n=int(input())
arr = list(map(int, input().split()))
print(rob(arr)), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array A of N positive integers. The task is to find a subsequence with maximum sum such that there should be no adjacent elements from the array in the subsequence.First line of input contains T, the number of test case.
First line of test case contains size of array N. Next line contains N space separated integers representing the elements of the array.
Constraints:
1 <= T <= 100
1 <= N <= 10^5
1 <= A[i] <= 10^6
<b>Sum of N over all testcases does not exceed 10^6</b>For each testcase, print the maximum sum of the subsequenceSample Input:-
2
3
1 2 3
3
1 20 3
Sample Output:-
4
20
Explanation:
Testcase 1: Elements 1 and 3 form a subsequence with maximum sum and no elements in the subsequence are adjacent in the array.
Testcase 2: Element 20 from the array forms a subsequence with maximum sum., I have written this Solution Code: #include "bits/stdc++.h"
#pragma GCC optimize "03"
using namespace std;
#define int long long int
#define ld long double
#define pi pair<int, int>
#define pb push_back
#define fi first
#define se second
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#ifndef LOCAL
#define endl '\n'
#endif
const int N = 2e5 + 5;
const int mod = 1e9 + 7;
const int inf = 1e9 + 9;
int dp[N][2];
signed main() {
IOS;
int t; cin >> t;
while(t--){
memset(dp, 0, sizeof dp);
int n; cin >> n;
for(int i = 1; i <= n; i++){
int p; cin >> p;
dp[i][1] = p + dp[i-1][0];
dp[i][0] = max(dp[i-1][0], dp[i-1][1]);
}
cout << max(dp[n][0], dp[n][1]) << endl;;
}
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a double linked list consisting of N nodes, your task is to reverse the linked list and return the head of the modified list.<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>Reverse()</b> that takes head node of the linked list as a parameter.
Constraints:
1 <= N <= 10^3
1<=value<=100Return the head of the modified linked list.Input:
6
1 2 3 4 5 6
Output:
6 5 4 3 2 1
Explanation:
After reversing the list, elements are as 6 <-> 5 <-> 4 <-> 3 <-> 2 <-> 1., I have written this Solution Code: public static Node Reverse(Node head) {
Node temp = null;
Node current = head;
while (current != null) {
temp = current.prev;
current.prev = current.next;
current.next = temp;
current = current.prev;
}
if (temp != null) {
head = temp.prev;
}
return head;
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a sorted doubly linked list containing n nodes. Your task is to remove duplicate nodes from the given list.
Example 1:
Input
1<->2<->2-<->3<->3<->4
Output:
1<->2<->3<->4
Example 2:
Input
1<->1<->1<->1
Output
1<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>deleteDuplicates()</b> that takes head node as parameter.
Constraints:
1 <=N <= 10000
1 <= Node. data<= 2*10000Return the head of the modified list.Sample Input:-
6
1 2 2 3 3 4
Sample Output:-
1 2 3 4
Sample Input:-
4
1 1 1 1
Sample Output:-
1, I have written this Solution Code: public static Node deleteDuplicates(Node head)
{
/* if list is empty */
if (head== null)
return head;
Node current = head;
while (current.next != null)
{
/* Compare current node with next node */
if (current.val == current.next.val)
/* delete the node pointed to by
' current->next' */
deleteNode(head, current.next);
/* else simply move to the next node */
else
current = current.next;
}
return head;
}
/* Function to delete a node in a Doubly Linked List.
head_ref --> pointer to head node pointer.
del --> pointer to node to be deleted. */
public static void deleteNode(Node head, Node del)
{
/* base case */
if(head==null || del==null)
{
return ;
}
/* If node to be deleted is head node */
if(head==del)
{
head=del.next;
}
/* Change next only if node to be deleted
is NOT the last node */
if(del.next!=null)
{
del.next.prev=del.prev;
}
/* Change prev only if node to be deleted
is NOT the first node */
if (del.prev != null)
del.prev.next = del.next;
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of N integers, your task is to calculate the sum of bit difference in all pairs which can be formed.The first line of input contains a single integer N, the second line of input contains N space separated integers depicting values of the array.
Constraints:-
1 <= N <= 100000
0 <= Arr[i] <= 1000000000Print the sum of bit difference of all possible pairs.
Note:- Since the answer can be quite large print your answer modulo 10<sup>9</sup> + 7Sample Input:-
2
1 3
Sample Output:-
2
Explanation:-
(1, 1) = 0
(1, 3) = 1
(3, 1) = 1
(3, 3) = 0
Sample Input:-
2
1 2
Sample Output:-
4, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
String str[]=br.readLine().split(" ");
int a[]=new int[n];
for(int i=0;i<n;i++){
a[i]=Integer.parseInt(str[i]);
}
long res=0;
for (int i=0;i<32;i++){
long cnt=0;
for (int j=0;j<n;j++)
if ((a[j] & (1 << i)) == 0)
cnt++;
res=(res+(cnt*(n-cnt)*2))%1000000007;
}
System.out.println(res%1000000007);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of N integers, your task is to calculate the sum of bit difference in all pairs which can be formed.The first line of input contains a single integer N, the second line of input contains N space separated integers depicting values of the array.
Constraints:-
1 <= N <= 100000
0 <= Arr[i] <= 1000000000Print the sum of bit difference of all possible pairs.
Note:- Since the answer can be quite large print your answer modulo 10<sup>9</sup> + 7Sample Input:-
2
1 3
Sample Output:-
2
Explanation:-
(1, 1) = 0
(1, 3) = 1
(3, 1) = 1
(3, 3) = 0
Sample Input:-
2
1 2
Sample Output:-
4, I have written this Solution Code: def suBD(arr, n):
ans = 0 # Initialize result
for i in range(0, 64):
count = 0
for j in range(0, n):
if ( (arr[j] & (1 << i)) ):
count+= 1
ans += (count * (n - count)) * 2;
return (ans)%(10**9+7)
n=int(input())
arr = map(int,input().split())
arr=list(arr)
print(suBD(arr, n)), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of N integers, your task is to calculate the sum of bit difference in all pairs which can be formed.The first line of input contains a single integer N, the second line of input contains N space separated integers depicting values of the array.
Constraints:-
1 <= N <= 100000
0 <= Arr[i] <= 1000000000Print the sum of bit difference of all possible pairs.
Note:- Since the answer can be quite large print your answer modulo 10<sup>9</sup> + 7Sample Input:-
2
1 3
Sample Output:-
2
Explanation:-
(1, 1) = 0
(1, 3) = 1
(3, 1) = 1
(3, 3) = 0
Sample Input:-
2
1 2
Sample Output:-
4, I have written this Solution Code:
#include <bits/stdc++.h>
using namespace std;
#define MEM(a, b) memset(a, (b), sizeof(a))
#define FOREACH(it, l) for (auto it = l.begin(); it != l.end(); it++)
#define IN(A, B, C) assert( B <= A && A <= C)
#define MP make_pair
#define FOR(i,a) for(int i=0;i<a;i++)
#define FOR1(i,j,a) for(int i=j;i<a;i++)
#define EB emplace_back
#define INF (int)1e9
#define EPS 1e-9
#define PI 3.1415926535897932384626433832795
#define max1 101
#define MOD 1000000007
#define read(type) readInt<type>()
#define out(x) cout<<x<<'\n'
#define out1(x) cout<<x<<" "
#define END cout<<'\n'
#define int long long
#define sz(v) ((int)(v).size())
#define all(v) (v).begin(), (v).end()
void fast(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}signed main(){
int N;
cin>>N;
int a[55];
int A[N];
FOR(i,N){
cin>>A[i];}
for(int i=0;i<55;i++){
a[i]=0;
}
int ans=1,p=2;
for(int i=0;i<55;i++){
for(int j=0;j<N;j++){
if(ans&A[j]){a[i]++;}
}
ans*=p;
// out(ans);
}
ans=0;
for(int i=0;i<55;i++){
ans+=(a[i]*(N-a[i])*2);
ans%=MOD;
}
out(ans);
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Power Rangers have to trap a evil spirit monster into a cuboid shape box with dimensions A*B*C, where A, B and C are positive integers. The volume of the box should be exactly X cubic units (that is A*B*C should be equal to X). To allow minimum evil aura to leak from the box the surface area of the box should be minimized. Given X, find the minimum surface area of the optimal box.The first and the only line of input contains a single integer X.
Constraints:
1 <= X <= 1000000Print the minimum surface area of the optimal box.Sample Input 1
125
Sample Output 1
150
Explanation: Optimal dimensions are 5*5*5.
Sample Input 2
100
Sample Output 1
130
Explanation: Optimal dimensions are 5*4*5., I have written this Solution Code:
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args)throws Exception{ new Main().run();}
long mod=1000000000+7;
long tsa=Long.MAX_VALUE;
void solve() throws Exception
{
long X=nl();
div(X);
out.println(tsa);
}
long cal(long a,long b, long c)
{
return 2l*(a*b + b*c + c*a);
}
void div(long n)
{
for (long i=1; i*i<=n; i++)
{
if (n%i==0)
{
if (n/i == i)
{
all_div(i, i);
}
else
{
all_div(i, n/i);
all_div(n/i, i);
}
}
}
}
void all_div(long n , long alag)
{
ArrayList<Long> al = new ArrayList<>();
for (long i=1; i*i<=n; i++)
{
if (n%i==0)
{
if (n/i == i)
tsa=min(tsa,cal(i,i,alag));
else
{
tsa=min(tsa,cal(i,n/i,alag));
}
}
}
}
private byte[] buf=new byte[1024];
private int index;
private InputStream in;
private int total;
private SpaceCharFilter filter;
PrintWriter out;
int min(int... ar){int min=Integer.MAX_VALUE;for(int i:ar)min=Math.min(min, i);return min;}
long min(long... ar){long min=Long.MAX_VALUE;for(long i:ar)min=Math.min(min, i);return min;}
int max(int... ar) {int max=Integer.MIN_VALUE;for(int i:ar)max=Math.max(max, i);return max;}
long max(long... ar) {long max=Long.MIN_VALUE;for(long i:ar)max=Math.max(max, i);return max;}
void reverse(int a[]){for(int i=0;i<a.length>>1;i++){int tem=a[i];a[i]=a[a.length-1-i];a[a.length-1-i]=tem;}}
void reverse(long a[]){for(int i=0;i<a.length>>1;i++){long tem=a[i];a[i]=a[a.length-1-i];a[a.length-1-i]=tem;}}
String reverse(String s){StringBuilder sb=new StringBuilder(s);sb.reverse();return sb.toString();}
void shuffle(int a[]) {
ArrayList<Integer> al = new ArrayList<>();
for(int i=0;i<a.length;i++)
al.add(a[i]);
Collections.sort(al);
for(int i=0;i<a.length;i++)
a[i]=al.get(i);
}
long lcm(long a,long b)
{
return (a*b)/(gcd(a,b));
}
int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
long expo(long p,long q)
{
long z = 1;
while (q>0) {
if (q%2 == 1) {
z = (z * p)%mod;
}
p = (p*p)%mod;
q >>= 1;
}
return z;
}
void run()throws Exception
{
in=System.in; out = new PrintWriter(System.out);
solve();
out.flush();
}
private int scan()throws IOException
{
if(total<0)
throw new InputMismatchException();
if(index>=total)
{
index=0;
total=in.read(buf);
if(total<=0)
return -1;
}
return buf[index++];
}
private int ni() throws IOException
{
int c = scan();
while (isSpaceChar(c))
c = scan();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = scan();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = scan();
} while (!isSpaceChar(c));
return res * sgn;
}
private long nl() throws IOException
{
long num = 0;
int b;
boolean minus = false;
while ((b = scan()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = scan();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = scan();
}
}
private double nd() throws IOException{
return Double.parseDouble(ns());
}
private String ns() throws IOException {
int c = scan();
while (isSpaceChar(c))
c = scan();
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c))
res.appendCodePoint(c);
c = scan();
} while (!isSpaceChar(c));
return res.toString();
}
private String nss() throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
return br.readLine();
}
private char nc() throws IOException
{
int c = scan();
while (isSpaceChar(c))
c = scan();
return (char) c;
}
private boolean isWhiteSpace(int n)
{
if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
return true;
return false;
}
private boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhiteSpace(c);
}
private interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Power Rangers have to trap a evil spirit monster into a cuboid shape box with dimensions A*B*C, where A, B and C are positive integers. The volume of the box should be exactly X cubic units (that is A*B*C should be equal to X). To allow minimum evil aura to leak from the box the surface area of the box should be minimized. Given X, find the minimum surface area of the optimal box.The first and the only line of input contains a single integer X.
Constraints:
1 <= X <= 1000000Print the minimum surface area of the optimal box.Sample Input 1
125
Sample Output 1
150
Explanation: Optimal dimensions are 5*5*5.
Sample Input 2
100
Sample Output 1
130
Explanation: Optimal dimensions are 5*4*5., I have written this Solution Code: m =int(input())
def print_factors(x):
factors=[]
for i in range(1, x + 1):
if x % i == 0:
factors.append(i)
return(factors)
area=[]
factors=print_factors(m)
for a in factors:
for b in factors:
for c in factors:
if(a*b*c==m):
area.append((2*a*b)+(2*b*c)+(2*a*c))
print(min(area)), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Power Rangers have to trap a evil spirit monster into a cuboid shape box with dimensions A*B*C, where A, B and C are positive integers. The volume of the box should be exactly X cubic units (that is A*B*C should be equal to X). To allow minimum evil aura to leak from the box the surface area of the box should be minimized. Given X, find the minimum surface area of the optimal box.The first and the only line of input contains a single integer X.
Constraints:
1 <= X <= 1000000Print the minimum surface area of the optimal box.Sample Input 1
125
Sample Output 1
150
Explanation: Optimal dimensions are 5*5*5.
Sample Input 2
100
Sample Output 1
130
Explanation: Optimal dimensions are 5*4*5., I have written this Solution Code: #pragma GCC optimize ("Ofast")
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define VV vector
#define pb push_back
#define bitc __builtin_popcountll
#define m_p make_pair
#define infi 1e18+1
#define eps 0.000000000001
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);
string char_to_str(char c){string tem(1,c);return tem;}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<class T>//usage rand<long long>()
T rand() {
return uniform_int_distribution<T>()(rng);
}
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template<class T>
using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
// string to integer stoi()
// string to long long stoll()
// string.substr(position,length);
// integer to string to_string();
//////////////
auto clk=clock();
#define all(x) x.begin(),x.end()
#define S second
#define F first
#define sz(x) ((long long)x.size())
#define int long long
#define f80 __float128
#define pii pair<int,int>
/////////////
signed main()
{
fastio;
#ifdef ANIKET_GOYAL
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
int x;
cin >> x;
int ans = 6*x*x;
for (int i=1;i*i*i<=x;++i)
if (x%i==0)
for (int j=i;j*j<=x/i;++j)
if (x/i % j==0) {
int k=x/i/j;
int cur=0;
cur=i*j+i*k+k*j;
cur*=2;
ans=min(ans,cur);
}
cout<<ans;
#ifdef ANIKET_GOYAL
// cout<<endl<<endl<<endl<<endl<<"Time elapsed: "<<(double)(clock()-clk)/CLOCKS_PER_SEC<<endl;
#endif
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Write a program to print Five stars ('*') <b><i>vertically</i></b> and 5 <b><i>horizontally</i></b>
There will be two functions:
<ul>
<li>verticalFive(): Print stars in vertical order</li>
<li>horizontalFive(): Print stars in horizontal order</l>
</ul><b>User Task:</b>
Your task is to complete the functions <b>verticalFive()</b> and <b>horizontalFive()</b>.
Print 5 vertical stars in <b> verticalFive</b> and 5 horizontal stars(separated by whitespace) in <b>horizontalFive</b> function.
<b>Note</b>: You don't need to print the extra blank line it will be printed by the driver codeNo Sample Input:
Sample Output:
*
*
*
*
*
* * * * *, I have written this Solution Code: static void verticalFive(){
System.out.println("*");
System.out.println("*");
System.out.println("*");
System.out.println("*");
System.out.println("*");
}
static void horizontalFive(){
System.out.print("* * * * *");
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Write a program to print Five stars ('*') <b><i>vertically</i></b> and 5 <b><i>horizontally</i></b>
There will be two functions:
<ul>
<li>verticalFive(): Print stars in vertical order</li>
<li>horizontalFive(): Print stars in horizontal order</l>
</ul><b>User Task:</b>
Your task is to complete the functions <b>verticalFive()</b> and <b>horizontalFive()</b>.
Print 5 vertical stars in <b> verticalFive</b> and 5 horizontal stars(separated by whitespace) in <b>horizontalFive</b> function.
<b>Note</b>: You don't need to print the extra blank line it will be printed by the driver codeNo Sample Input:
Sample Output:
*
*
*
*
*
* * * * *, I have written this Solution Code: def vertical5():
for i in range(0,5):
print("*",end="\n")
#print()
def horizontal5():
for i in range(0,5):
print("*",end=" ")
vertical5()
print(end="\n")
horizontal5(), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Find factorial of a given number N.
<b>Note: </b>
The Factorial of a number is the product of an integer and all the integers below it;
e.g. factorial four ( 4! ) is equal to 24 (4*3*2*1).<b>User Task</b>
Since this is a functional problem, you don't have to worry about the input. You just have to complete the function <i>Factorial()</i> which contains the given number N.
<b>Constraints:</b>
1 <= N <= 15
Return the factorial of the given number.Sample Input:-
5
Sample Output:-
120
Sample Input:-
3
Sample Output:-
6, I have written this Solution Code: def factorial(n):
if(n == 1):
return 1
return n * factorial(n-1)
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Find factorial of a given number N.
<b>Note: </b>
The Factorial of a number is the product of an integer and all the integers below it;
e.g. factorial four ( 4! ) is equal to 24 (4*3*2*1).<b>User Task</b>
Since this is a functional problem, you don't have to worry about the input. You just have to complete the function <i>Factorial()</i> which contains the given number N.
<b>Constraints:</b>
1 <= N <= 15
Return the factorial of the given number.Sample Input:-
5
Sample Output:-
120
Sample Input:-
3
Sample Output:-
6, I have written this Solution Code: static int Factorial(int N)
{
if(N==0){
return 1;}
return N*Factorial(N-1);
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Find factorial of a given number N.
<b>Note: </b>
The Factorial of a number is the product of an integer and all the integers below it;
e.g. factorial four ( 4! ) is equal to 24 (4*3*2*1).<b>User Task</b>
Since this is a functional problem, you don't have to worry about the input. You just have to complete the function <i>Factorial()</i> which contains the given number N.
<b>Constraints:</b>
1 <= N <= 15
Return the factorial of the given number.Sample Input:-
5
Sample Output:-
120
Sample Input:-
3
Sample Output:-
6, I have written this Solution Code: // n is the input number
function factorial(n) {
// write code here
// do not console.log
// return the answer as a number
if (n == 1 ) return 1;
return n * factorial(n-1)
}, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a string S you have to remove all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, remove them as well. Repeat this untill no adjacent letter in the string is same.
Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result.The input data consists of a single string S.
Constraints:
1 <= |S| <= 100000
S contains lowercase english letters only.Print the given string after it is processed. It is guaranteed that the result will contain at least one character.Sample Input
hhoowaaaareyyoouu
Sample Output
wre
Explanation:
First we remove "hh" then "oo" then "aa" then "yy" then "oo" then "uu" and we are left with "wre".
Now we cannot remove anything.
Sample Input:-
abcde
Sample Output:-
abcde
Sample Input:-
abcddcb
Sample Output:-
a, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws IOException {
BufferedReader in =new BufferedReader(new InputStreamReader(System.in));
StringBuilder s = new StringBuilder();
String text=null;
while ((text = in.readLine ()) != null)
{
s.append(text);
}
int len=s.length();
for(int i=0;i<len-1;i++){
if(s.charAt(i)==s.charAt(i+1)){
int flag=0;
s.delete(i,i+2);
int left=i-1;
len=len-2;
i=i-2;
if(i<0){
i=-1;
}
}
}
System.out.println(s);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a string S you have to remove all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, remove them as well. Repeat this untill no adjacent letter in the string is same.
Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result.The input data consists of a single string S.
Constraints:
1 <= |S| <= 100000
S contains lowercase english letters only.Print the given string after it is processed. It is guaranteed that the result will contain at least one character.Sample Input
hhoowaaaareyyoouu
Sample Output
wre
Explanation:
First we remove "hh" then "oo" then "aa" then "yy" then "oo" then "uu" and we are left with "wre".
Now we cannot remove anything.
Sample Input:-
abcde
Sample Output:-
abcde
Sample Input:-
abcddcb
Sample Output:-
a, I have written this Solution Code: s=input()
l=["aa","bb","cc","dd","ee","ff","gg","hh","ii","jj","kk","ll","mm","nn","oo","pp","qq","rr","ss","tt","uu","vv","ww","xx","yy","zz"]
while True:
do=False
for i in range(len(l)):
if l[i] in s:
do=True
while l[i] in s:
s=s.replace(l[i],"")
if do==False:
break
print(s), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a string S you have to remove all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, remove them as well. Repeat this untill no adjacent letter in the string is same.
Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result.The input data consists of a single string S.
Constraints:
1 <= |S| <= 100000
S contains lowercase english letters only.Print the given string after it is processed. It is guaranteed that the result will contain at least one character.Sample Input
hhoowaaaareyyoouu
Sample Output
wre
Explanation:
First we remove "hh" then "oo" then "aa" then "yy" then "oo" then "uu" and we are left with "wre".
Now we cannot remove anything.
Sample Input:-
abcde
Sample Output:-
abcde
Sample Input:-
abcddcb
Sample Output:-
a, I have written this Solution Code: #pragma GCC optimize ("Ofast")
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define VV vector
#define pb push_back
#define bitc __builtin_popcountll
#define m_p make_pair
#define infi 1e18+1
#define eps 0.000000000001
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);
string char_to_str(char c){string tem(1,c);return tem;}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<class T>//usage rand<long long>()
T rand() {
return uniform_int_distribution<T>()(rng);
}
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template<class T>
using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
// string to integer stoi()
// string to long long stoll()
// string.substr(position,length);
// integer to string to_string();
//////////////
auto clk=clock();
#define all(x) x.begin(),x.end()
#define S second
#define F first
#define sz(x) ((long long)x.size())
#define int long long
#define f80 __float128
#define pii pair<int,int>
/////////////
signed main(){
fastio;
#ifdef ANIKET_GOYAL
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
string s;
cin>>s;
int len=s.length();
char stk[410000];
int k = 0;
for (int i = 0; i < len; i++)
{
stk[k++] = s[i];
while (k > 1 && stk[k - 1] == stk[k - 2])
k -= 2;
}
for (int i = 0; i < k; i++)
cout << stk[i];
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: <i>We didn't like the final season much, so finale isn't GOT! :P </i>
Making a sword involves three stages, forging it, carrying it to polishing center and then polishing it. There are two types of swords that must be made.
Forging sword 1 and sword 2 takes X hours.
Carrying sword 1 from forging centre to polishing centre takes T1 hours.
Carrying sword 2 from forging centre to polishing centre takes T2 hours.
Polishing sword 1 and sword 2 takes X hours.
No two swords can be in same stage at a time, but two swords can be in different stages in parallel.
Thomas is required to make A swords of type 1 and B swords of type 2. Find the minimum time required by Thomas to make all the swords. You can make swords in any order.Input contains 5 integers X T1 T2 A B.
Constraints:
1 <= X, T1, T2 <= 10000
1 <= A, B <= 100000The minimum time required to produce the required swords.Sample Input
6 4 8 2 2
Sample Output
38
Explanation: Optimal order is sword 2 sword 1 sword 1 sword 2.
First sword will be finished forging after 6 hours.
First sword will be finished transporting after 14 hours.
First sword will be finished polishing after 20 hours.
Second sword can enter forging after 6 hours so it will be finished forging at 12 hours.
Second sword can enter transporting after 14 hours so it will be finished transporting at 18 hours.
Second sword can enter polishing after 20 hours so it will be finished polishing at 26 hours.
Third sword can enter forging after 12 hours so it will be finished forging at 18 hours.
Third sword can enter transporting after 18 hours so it will be finished transporting at 22 hours.
Third sword can enter polishing after 26 hours so it will be finished polishing at 32 hours.
Fourth sword can enter forging after 18 hours so it will be finished forging at 24 hours.
Fourth sword can enter transporting after 24 hours so it will be finished transporting at 32 hours.
Fourth sword can enter polishing after 32 hours so it will be finished polishing at 38 hours., I have written this Solution Code: #pragma GCC optimize ("Ofast")
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define VV vector
#define pb push_back
#define bitc __builtin_popcountll
#define m_p make_pair
#define infi 1e18+1
#define eps 0.000000000001
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);
string char_to_str(char c){string tem(1,c);return tem;}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<class T>//usage rand<long long>()
T rand() {
return uniform_int_distribution<T>()(rng);
}
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template<class T>
using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
// string to integer stoi()
// string to long long stoll()
// string.substr(position,length);
// integer to string to_string();
//////////////
template<class C> void mini(C&a4, C b4){a4=min(a4,b4);}
typedef unsigned long long ull;
auto clk=clock();
#define all(x) x.begin(),x.end()
#define S second
#define F first
#define sz(x) ((long long)x.size())
#define int long long
#define f80 __float128
#define pii pair<int,int>
/////////////
int t,c1,c2,a1,a2;
bool spr(int x){
int zapas = x;
int b1 = a1;
int b2 = a2;
while(b1 || b2){
mini(zapas,x);
if(b2 && zapas >= c2){
zapas -= c2;
b2--;
}else{
if(b1 == 0 || zapas < c1){
return 0;
}
zapas -= c1;
b1--;
}
zapas += t;
}
return 1;
}
signed main(){
#ifdef ANIKET_GOYAL
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
cin >> t >> c1 >> c2 >> a1 >> a2;
if(a1 + a2 == 0){
cout << "0\n";
return 0;
}
int po = 0;
int ko = 2e9;
while(po+1 < ko){
int m = (po+ko) >>1;
if(spr(m))
ko = m;
else
po = m;
}
cout << t*(a1+a2+1) + ko << endl;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a positive integer N. You need to print the sum of the first N natural numbers.The first line of input contains a single integer T, the next T lines contains a single integer N.
Constraints:
1 < = T < = 100
1 < = N < = 100Print the sum of first N natural numbers for each test case in a new line.Sample Input:
2
5
10
Sample Output:
15
55, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args)throws IOException {
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine());
while(t-->0){
int n=Integer.parseInt(br.readLine());
System.out.println(n*(n+1)/2);
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a positive integer N. You need to print the sum of the first N natural numbers.The first line of input contains a single integer T, the next T lines contains a single integer N.
Constraints:
1 < = T < = 100
1 < = N < = 100Print the sum of first N natural numbers for each test case in a new line.Sample Input:
2
5
10
Sample Output:
15
55, I have written this Solution Code: for t in range(int(input())):
n = int(input())
print(n*(n+1)//2), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a positive integer N. You need to print the sum of the first N natural numbers.The first line of input contains a single integer T, the next T lines contains a single integer N.
Constraints:
1 < = T < = 100
1 < = N < = 100Print the sum of first N natural numbers for each test case in a new line.Sample Input:
2
5
10
Sample Output:
15
55, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
cout<<(n*(n+1))/2<<endl;
}
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a boolean Matrix of size N*M, A cell of the matrix is called "Good" if it is completely surrounded by the cells containing '1' i.e. each adjacent cell (which shares a common edge) contains '1'. Your task is to find the number of such cells.
See the below example for a better understandingFirst line of input contains two space- separated integers N and M. Next N lines of input contain M space- separated integers depicting the values of the matrix.
Constraints:-
3 <= N, M <= 500
0 <= Matrix[][] <= 1Print the number of good cells.Sample Input:-
3 3
1 1 0
1 1 1
1 1 1
Sample Output:-
1
Explanation:-
Only cell at position 1, 1 is good
Sample Input:-
5 4
1 0 1 0
0 1 0 1
1 0 1 0
0 1 0 1
1 0 1 0
Sample Output:-
3
Explanation:-
(1, 2), (2, 1) and (3, 2) are good cells, I have written this Solution Code: // mat is the matrix/ 2d array
// n,m are dimensions
function goodCell(mat, n, m) {
// write code here
// do not console.log
// return the answer as a number
let cnt = 0;
for (let i = 1; i < n - 1; i++) {
for (let j = 1; j < m - 1; j++) {
if (mat[i - 1][j] == 1 && mat[i + 1][j] == 1 && mat[i][j - 1] == 1 && mat[i][j + 1] == 1) {
cnt++;
}
}
}
return cnt
}
, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a boolean Matrix of size N*M, A cell of the matrix is called "Good" if it is completely surrounded by the cells containing '1' i.e. each adjacent cell (which shares a common edge) contains '1'. Your task is to find the number of such cells.
See the below example for a better understandingFirst line of input contains two space- separated integers N and M. Next N lines of input contain M space- separated integers depicting the values of the matrix.
Constraints:-
3 <= N, M <= 500
0 <= Matrix[][] <= 1Print the number of good cells.Sample Input:-
3 3
1 1 0
1 1 1
1 1 1
Sample Output:-
1
Explanation:-
Only cell at position 1, 1 is good
Sample Input:-
5 4
1 0 1 0
0 1 0 1
1 0 1 0
0 1 0 1
1 0 1 0
Sample Output:-
3
Explanation:-
(1, 2), (2, 1) and (3, 2) are good cells, I have written this Solution Code: N, M= list(map(int,input().split()))
mat =[]
for i in range(N):
List =list(map(int,input().split()))[:M]
mat.append(List)
count =0
for i in range(1,N-1):
for j in range(1,M-1):
if (mat[i][j-1] == 1 and mat[i][j+1] == 1 and mat[i-1][j] == 1 and mat[i+1][j] == 1):
count +=1
print(count), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a boolean Matrix of size N*M, A cell of the matrix is called "Good" if it is completely surrounded by the cells containing '1' i.e. each adjacent cell (which shares a common edge) contains '1'. Your task is to find the number of such cells.
See the below example for a better understandingFirst line of input contains two space- separated integers N and M. Next N lines of input contain M space- separated integers depicting the values of the matrix.
Constraints:-
3 <= N, M <= 500
0 <= Matrix[][] <= 1Print the number of good cells.Sample Input:-
3 3
1 1 0
1 1 1
1 1 1
Sample Output:-
1
Explanation:-
Only cell at position 1, 1 is good
Sample Input:-
5 4
1 0 1 0
0 1 0 1
1 0 1 0
0 1 0 1
1 0 1 0
Sample Output:-
3
Explanation:-
(1, 2), (2, 1) and (3, 2) are good cells, I have written this Solution Code:
#include <bits/stdc++.h>
using namespace std;
#define MEM(a, b) memset(a, (b), sizeof(a))
#define FOREACH(it, l) for (auto it = l.begin(); it != l.end(); it++)
#define IN(A, B, C) assert( B <= A && A <= C)
#define MP make_pair
#define FOR(i,a) for(int i=0;i<a;i++)
#define FOR1(i,j,a) for(int i=j;i<a;i++)
#define EB emplace_back
#define INF (int)1e9
#define EPS 1e-9
#define PI 3.1415926535897932384626433832795
#define max1 1000001
#define MOD 1000000007
#define read(type) readInt<type>()
#define out(x) cout<<x<<'\n'
#define out1(x) cout<<x<<" "
#define END cout<<'\n'
#define int long long
#define sz(v) ((int)(v).size())
#define all(v) (v).begin(), (v).end()
void fast(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}
signed main(){
int n,m;
cin>>n>>m;
int a[n][m];
FOR(i,n){
FOR(j,m){
cin>>a[i][j];}}
int sum=0,sum1=0;;
FOR1(i,1,n-1){
FOR1(j,1,m-1){
if(a[i-1][j]==1 && a[i+1][j]==1 && a[i][j-1]==1 && a[i][j+1]==1){
sum++;
}
}
}
out1(sum);
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a boolean Matrix of size N*M, A cell of the matrix is called "Good" if it is completely surrounded by the cells containing '1' i.e. each adjacent cell (which shares a common edge) contains '1'. Your task is to find the number of such cells.
See the below example for a better understandingFirst line of input contains two space- separated integers N and M. Next N lines of input contain M space- separated integers depicting the values of the matrix.
Constraints:-
3 <= N, M <= 500
0 <= Matrix[][] <= 1Print the number of good cells.Sample Input:-
3 3
1 1 0
1 1 1
1 1 1
Sample Output:-
1
Explanation:-
Only cell at position 1, 1 is good
Sample Input:-
5 4
1 0 1 0
0 1 0 1
1 0 1 0
0 1 0 1
1 0 1 0
Sample Output:-
3
Explanation:-
(1, 2), (2, 1) and (3, 2) are good cells, I have written this Solution Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m= sc.nextInt();
int a[][]= new int[n][m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
a[i][j]=sc.nextInt();}}
int cnt=0;
for(int i=1;i<n-1;i++){
for(int j=1;j<m-1;j++){
if(a[i-1][j]==1 && a[i+1][j]==1 && a[i][j-1]==1 && a[i][j+1]==1){
cnt++;
}
}
}
System.out.print(cnt);
}
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You need to make an order counter to keep track of the total number of orders received.
Complete the function <code> generateOrder() </code> which returns a <code>function func()</code>. This function <code>func</code> should maintain a <code> count (initially 0)</code>. Every time <code>func</code> is called, <code> count</code> must be incremented by 1 and the string <code>"Total orders = " + count</code> must be returned.
<b>Note:</b> The function generateOrder() will be called internally. You do not need to call it yourself. The generateOrder() takes no argument. It is called internally.The generateOrder() function returns a function that returns the string <code>"Total orders = " + count</code>, where <code>count</code> is the number of times the function is called.
const initC = generateOrder(starting);
console.log(initC()) //prints "Total orders = 1"
console.log(initC()) //prints "Total orders = 2"
console.log(initC()) //prints "Total orders = 3"
, I have written this Solution Code: let generateOrder = function() {
let prefix = "Total orders = ";
let count = 0;
let totalOrders = function(){
count++
return prefix + count;
}
return totalOrders;
}, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Ronaldo has challenged Messi to beat his team in the upcoming “Friendly” fixture. But both these legends are tired of the original football rules, so they decided to play Football with a twist. Each player is assigned an ID, from 1 to 10^6. Initially Ronaldo has the ball in his posession. Given a sequence of N passes, help Messi Know which ID player has the ball, after N passes.
Note: Passes are of two types :
i) P ID, which means the player currently having the ball passes it to Player with identity ID.
ii) B, which means the player currently having the ball passes it back to the Player he got the Pass From.
Also, It is guaranteed that the given order of passes will be a valid order.The first line of input contains number of testcases T. The 1st line of each testcase, contains two integers, N and ID1, denoting the total number of passes and the ID of Ronaldo. Respectively. Each of the next N lines, contains the information of a Pass which can be either of the above two types, i.e:
1) P ID
2) B
Constraints
1 <= T <= 100
1 <= N <= 10^5
1 <= IDs <= 10^6
Sum of N for every test case is less than 10^6For each testcase you need to print the ID of the Player having the ball after N passes.Input :
2
3 1
P 13
P 14
B
5 1
P 12
P 13
P 14
B
B
Output :
13
14
Explanation :
Testcase 1: Initially, the ball is with Ronaldo, having ID 1.
In the first pass, he passes the ball to Player with ID 13.
In the Second Pass, the player currently having the ball, ie Player with ID 13, passes it to player with ID 14.
In the last pass the player currently having the ball, ie Player with ID 14 passed the ball back to the player from whom he got the Pass, i.e the ball is passed back to Player with Player ID 13, as Player ID 13 had passed the ball to player ID 14 in the previous pass.
Testcase 2: Initially, the ball is with Ronaldo, having ID 1.
In the first pass he passes the ball to player with ID 12.
In the second pass, the second player passes the ball to palyer with ID 13, again the player with ID 13 passes the ball to player with ID 14.
Now, player with ID 14 passed back the ball to 13, and again 13 passes back the ball to 14., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine().trim());
while (t-- > 0) {
String[] line = br.readLine().trim().split(" ");
int n = Integer.parseInt(line[0]);
int curr = Integer.parseInt(line[1]);
int prev = curr;
while (n-- > 0) {
String[] currLine = br.readLine().trim().split(" ");
if (currLine[0].equals("P")) {
prev = curr;
curr = Integer.parseInt(currLine[1]);
}
if (currLine[0].equals("B")) {
int temp = curr;
curr = prev;
prev = temp;
}
}
System.out.println(curr);
System.gc();
}
br.close();
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Ronaldo has challenged Messi to beat his team in the upcoming “Friendly” fixture. But both these legends are tired of the original football rules, so they decided to play Football with a twist. Each player is assigned an ID, from 1 to 10^6. Initially Ronaldo has the ball in his posession. Given a sequence of N passes, help Messi Know which ID player has the ball, after N passes.
Note: Passes are of two types :
i) P ID, which means the player currently having the ball passes it to Player with identity ID.
ii) B, which means the player currently having the ball passes it back to the Player he got the Pass From.
Also, It is guaranteed that the given order of passes will be a valid order.The first line of input contains number of testcases T. The 1st line of each testcase, contains two integers, N and ID1, denoting the total number of passes and the ID of Ronaldo. Respectively. Each of the next N lines, contains the information of a Pass which can be either of the above two types, i.e:
1) P ID
2) B
Constraints
1 <= T <= 100
1 <= N <= 10^5
1 <= IDs <= 10^6
Sum of N for every test case is less than 10^6For each testcase you need to print the ID of the Player having the ball after N passes.Input :
2
3 1
P 13
P 14
B
5 1
P 12
P 13
P 14
B
B
Output :
13
14
Explanation :
Testcase 1: Initially, the ball is with Ronaldo, having ID 1.
In the first pass, he passes the ball to Player with ID 13.
In the Second Pass, the player currently having the ball, ie Player with ID 13, passes it to player with ID 14.
In the last pass the player currently having the ball, ie Player with ID 14 passed the ball back to the player from whom he got the Pass, i.e the ball is passed back to Player with Player ID 13, as Player ID 13 had passed the ball to player ID 14 in the previous pass.
Testcase 2: Initially, the ball is with Ronaldo, having ID 1.
In the first pass he passes the ball to player with ID 12.
In the second pass, the second player passes the ball to palyer with ID 13, again the player with ID 13 passes the ball to player with ID 14.
Now, player with ID 14 passed back the ball to 13, and again 13 passes back the ball to 14., I have written this Solution Code: for i in range(int(input())):
N, ID = map(int,input().split())
pre = 0
for i in range(N):
arr = input().split()
if len(arr)==2:
pre,ID = ID,arr[1]
else:
ID,pre = pre,ID
print(ID) if pre else print(0), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Ronaldo has challenged Messi to beat his team in the upcoming “Friendly” fixture. But both these legends are tired of the original football rules, so they decided to play Football with a twist. Each player is assigned an ID, from 1 to 10^6. Initially Ronaldo has the ball in his posession. Given a sequence of N passes, help Messi Know which ID player has the ball, after N passes.
Note: Passes are of two types :
i) P ID, which means the player currently having the ball passes it to Player with identity ID.
ii) B, which means the player currently having the ball passes it back to the Player he got the Pass From.
Also, It is guaranteed that the given order of passes will be a valid order.The first line of input contains number of testcases T. The 1st line of each testcase, contains two integers, N and ID1, denoting the total number of passes and the ID of Ronaldo. Respectively. Each of the next N lines, contains the information of a Pass which can be either of the above two types, i.e:
1) P ID
2) B
Constraints
1 <= T <= 100
1 <= N <= 10^5
1 <= IDs <= 10^6
Sum of N for every test case is less than 10^6For each testcase you need to print the ID of the Player having the ball after N passes.Input :
2
3 1
P 13
P 14
B
5 1
P 12
P 13
P 14
B
B
Output :
13
14
Explanation :
Testcase 1: Initially, the ball is with Ronaldo, having ID 1.
In the first pass, he passes the ball to Player with ID 13.
In the Second Pass, the player currently having the ball, ie Player with ID 13, passes it to player with ID 14.
In the last pass the player currently having the ball, ie Player with ID 14 passed the ball back to the player from whom he got the Pass, i.e the ball is passed back to Player with Player ID 13, as Player ID 13 had passed the ball to player ID 14 in the previous pass.
Testcase 2: Initially, the ball is with Ronaldo, having ID 1.
In the first pass he passes the ball to player with ID 12.
In the second pass, the second player passes the ball to palyer with ID 13, again the player with ID 13 passes the ball to player with ID 14.
Now, player with ID 14 passed back the ball to 13, and again 13 passes back the ball to 14., I have written this Solution Code: #include "bits/stdc++.h"
#pragma GCC optimize "03"
using namespace std;
#define int long long int
#define ld long double
#define pi pair<int, int>
#define pb push_back
#define fi first
#define se second
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#ifndef LOCAL
#define endl '\n'
#endif
const int N = 2e5 + 5;
const int mod = 1e9 + 7;
const int inf = 1e9 + 9;
signed main() {
IOS;
int t; cin >> t;
while(t--){
int n, id; cin >> n >> id;
int pre = 0, cur = id;
for(int i = 1; i <= n; i++){
char c; cin >> c;
if(c == 'P'){
int x; cin >> x;
pre = cur;
cur = x;
}
else{
swap(pre, cur);
}
}
cout << cur << endl;
}
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a binary matrix, your task is to calculate the maximum area of a rectangle formed by only 1's in it.First line contains two integers number of rows N and number of columns M.
Next N lines contain M integers with each integer being either 0 or 1
Constraints:-
1 <= N, M <=1000Print the maximum area of rectangle.Sample Input 1:
4 4
0 1 1 0
1 1 1 1
1 1 1 1
1 1 0 0
Sample Output 1:
8
Explanation
The max size rectangle is
1 1 1 1
1 1 1 1
and its area is 4*2 = 8
Sample Input 2:-
1 4
1 1 1 1
Sample Output 2:-
4, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main { static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main (String[] args) {
FastReader sc = new FastReader();
int n = sc.nextInt();int m = sc.nextInt();
char a[][] = new char[n][m];
for(int i=0;i<n;i++){for(int j=0;j<m;j++){
a[i][j] = sc.next().charAt(0);
}}
System.out.println(findRectangleArea2Ds(a));
}
private static int findRectangleArea2Ds(char[][] matrix) {
if (matrix == null || matrix.length == 0) {
return 0;
}
int maxArea = 0;
int rows = matrix.length;
int cols = matrix[0].length;
int[][] dp = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix[i][j] == '1') {
dp[i][j] = j == 0 ? 1 : dp[i][j - 1] + 1;
int length = dp[i][j];
for (int k = i; k >= 0; k--) {
length = Math.min(length, dp[k][j]);
int width = i - k + 1;
maxArea = Math.max(maxArea, length * width);
}
}
}
}
return maxArea;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a binary matrix, your task is to calculate the maximum area of a rectangle formed by only 1's in it.First line contains two integers number of rows N and number of columns M.
Next N lines contain M integers with each integer being either 0 or 1
Constraints:-
1 <= N, M <=1000Print the maximum area of rectangle.Sample Input 1:
4 4
0 1 1 0
1 1 1 1
1 1 1 1
1 1 0 0
Sample Output 1:
8
Explanation
The max size rectangle is
1 1 1 1
1 1 1 1
and its area is 4*2 = 8
Sample Input 2:-
1 4
1 1 1 1
Sample Output 2:-
4, I have written this Solution Code: #include "bits/stdc++.h"
#pragma GCC optimize "03"
using namespace std;
#define int long long int
#define ld long double
#define pi pair<int, int>
#define pb push_back
#define fi first
#define se second
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#ifndef LOCAL
#define endl '\n'
#endif
const int N = 1e3 + 5;
const int mod = 1e9 + 7;
const int inf = 1e9 + 9;
int p[N][N], l[N], r[N];
signed main() {
IOS;
int n, m;
cin >> n >> m;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
cin >> p[i][j];
if(p[i][j])
p[i][j] += p[i-1][j];
}
}
int ans = 0;
for(int i = 1; i <= n; i++){
memset(l, 0, sizeof l);
memset(r, 0, sizeof r);
stack<int> s;
p[i][0] = p[i][m+1] = -1;
s.push(0);
for(int j = 1; j <= m; j++){
while(!s.empty() && p[i][s.top()] >= p[i][j])
s.pop();
l[j] = s.top();
s.push(j);
}
while(!s.empty())
s.pop();
s.push(m+1);
for(int j = m; j >= 1; j--){
while(!s.empty() && p[i][s.top()] >= p[i][j])
s.pop();
r[j] = s.top();
s.push(j);
}
for(int j = 1; j <= m; j++)
ans = max(ans, p[i][j]*(r[j]-l[j]-1));
}
cout << ans;
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of N integers, an integer X, and Q queries. For each query, you will be given an integer K. Your task is to find the Kth occurrence of the number X in the array. If the Kth occurrence does not exist print -1.The first line of input contains three integers N, X, and Q. The second line of input contains N space- separated integers. The Next Q lines of input contain a single integer each representing K.
Constraints:-
1 <= Q, K, N <= 100000
1 <= X, Arr[] <= 100000For each query in a new line print the index of the Kth occurrence. If the Kth occurrence does not exist print -1.Sample Input:-
10 3 4
1 2 3 4 2 3 4 5 2 3
1
2
3
4
Sample Output:_
3
6
10
-1, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws IOException {
BufferedReader inp = new BufferedReader(new InputStreamReader(System.in));
String[] NXQ = inp.readLine().split("\\s+");
int N = Integer.parseInt(NXQ[0]);
int X = Integer.parseInt(NXQ[1]);
int Q = Integer.parseInt(NXQ[2]);
String[] StrArr = inp.readLine().split("\\s+");
int[] arr = new int[N];
ArrayList<Integer> posX = new ArrayList<>();
int j = 0;
for (int i = 0; i < N; i++) {
arr[i] = Integer.parseInt(StrArr[i]);
if (arr[i] == X) {
posX.add(i + 1);
}
}
for (int i = 0; i < Q; i++) {
int query = Integer.parseInt(inp.readLine());
if (query > posX.size()) {
System.out.println("-1");
}
else {
System.out.println(posX.get(query - 1));
}
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of N integers, an integer X, and Q queries. For each query, you will be given an integer K. Your task is to find the Kth occurrence of the number X in the array. If the Kth occurrence does not exist print -1.The first line of input contains three integers N, X, and Q. The second line of input contains N space- separated integers. The Next Q lines of input contain a single integer each representing K.
Constraints:-
1 <= Q, K, N <= 100000
1 <= X, Arr[] <= 100000For each query in a new line print the index of the Kth occurrence. If the Kth occurrence does not exist print -1.Sample Input:-
10 3 4
1 2 3 4 2 3 4 5 2 3
1
2
3
4
Sample Output:_
3
6
10
-1, I have written this Solution Code: N, X , Q = map(int, input().split())
L = list(map(int, input().split()))
Queries = []
while Q > 0:
Queries.append(int(input()))
Q -= 1
indices = [i for i,x in enumerate(L) if x == X]
for query in Queries:
if len(indices)< query:
print(-1)
else:
print(indices[query-1]+1), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of N integers, an integer X, and Q queries. For each query, you will be given an integer K. Your task is to find the Kth occurrence of the number X in the array. If the Kth occurrence does not exist print -1.The first line of input contains three integers N, X, and Q. The second line of input contains N space- separated integers. The Next Q lines of input contain a single integer each representing K.
Constraints:-
1 <= Q, K, N <= 100000
1 <= X, Arr[] <= 100000For each query in a new line print the index of the Kth occurrence. If the Kth occurrence does not exist print -1.Sample Input:-
10 3 4
1 2 3 4 2 3 4 5 2 3
1
2
3
4
Sample Output:_
3
6
10
-1, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
#define int long long
signed main(){
int n,x,q;
cin>>n>>x>>q;
vector<int> a(n),v;
for(int i=0;i<n;i++){
cin>>a[i];
if(a[i]==x){
v.push_back(i+1);
}
}
while(q--){
cin>>x;
if(x<=v.size()){
cout<<v[x-1]<<'\n';
}
else{
cout<<-1<<'\n';
}
}
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Tono loves to do shopping. Today, she went to the market where there are N different types of products. She wants to buy exactly K of them at the minimum cost. Although she is super smart, she wants to check your smartness as well. Can you tell her the minimum cost required to buy exactly K products if she has already decided to buy product J?
<b>Note:</b> Tono does not buy the same product twice, and Tono will definitely buy product J (J is the <b>index</b> of the item).The first line of the input contains three integers, N, K, and J, denoting the number of products in the market, the number of products Tono needs to buy, and the product that Tono will definitely buy.
The next line contains N singly spaced integers, the cost of the N products C[1], C[2], ..., C[N].
<b>Constraints:</b>
1 <= N <= 200000
1 <= K <= N
1 <= J <= N
1 <= C[i] <= 1000
Output a single integer, the minimum amount Tono needs to pay.Sample Input 1:
5 3 4
1 2 3 4 5
Sample Output 1:
7
Sample Input 2:
5 1 3
2 4 3 1 1
Sample Output 2:
3
<b>Explanation:</b>
Tono needs to buy exactly 3 products, and she will definitely buy the 4th product. Thus, she will buy the 1st, 2nd, and the 4th product. The total cost she pays is 1+2+4=7.
, I have written this Solution Code: import java.util.*;
import java.io.*;
class Main {
public static void main(String[] args) throws IOException {
int n = io.nextInt(), k = io.nextInt(), j = io.nextInt() - 1;
int[] arr = new int[n];
for(int i = 0; i < n; i++) {
arr[i] = io.nextInt();
}
int cost = arr[j];
arr[j] = Integer.MAX_VALUE;
Arrays.sort(arr);
for(int i = 0; i < k - 1; i++) {
cost += arr[i];
}
io.println(cost);
io.close();
}
static IO io = new IO();
static class IO {
private byte[] buf;
private InputStream in;
private PrintWriter pw;
private int total, index;
public IO() {
buf = new byte[1024];
in = System.in;
pw = new PrintWriter(System.out);
}
public int next() throws IOException {
if(total < 0)
throw new InputMismatchException();
if(index >= total) {
index = 0;
total = in.read(buf);
if(total <= 0)
return -1;
}
return buf[index++];
}
public int nextInt() throws IOException {
int n = next(), integer = 0;
while(isWhiteSpace(n))
n = next();
int neg = 1;
if(n == '-') {
neg = -1;
n = next();
}
while(!isWhiteSpace(n)) {
if(n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = next();
}
else
throw new InputMismatchException();
}
return neg * integer;
}
public int[] nextIntArray(int n) throws IOException {
int[] arr = new int[n];
for(int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
public long nextLong() throws IOException {
long integer = 0l;
int n = next();
while(isWhiteSpace(n))
n = next();
int neg = 1;
if(n == '-') {
neg = -1;
n = next();
}
while(!isWhiteSpace(n)) {
if(n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = next();
}
else
throw new InputMismatchException();
}
return neg * integer;
}
public double nextDouble() throws IOException {
double doub = 0;
int n = next();
while(isWhiteSpace(n))
n = next();
int neg = 1;
if(n == '-') {
neg = -1;
n = next();
}
while(!isWhiteSpace(n) && n != '.') {
if(n >= '0' && n <= '9') {
doub *= 10;
doub += n - '0';
n = next();
}
else
throw new InputMismatchException();
}
if(n == '.') {
n = next();
double temp = 1;
while(!isWhiteSpace(n)) {
if(n >= '0' && n <= '9') {
temp /= 10;
doub += (n - '0') * temp;
n = next();
}
else
throw new InputMismatchException();
}
}
return doub * neg;
}
public String nextString() throws IOException {
StringBuilder sb = new StringBuilder();
int n = next();
while(isWhiteSpace(n))
n = next();
while(!isWhiteSpace(n)) {
sb.append((char)n);
n = next();
}
return sb.toString();
}
public String nextLine() throws IOException {
int n = next();
while(isWhiteSpace(n))
n = next();
StringBuilder sb = new StringBuilder();
while(!isEndOfLine(n)) {
sb.append((char)n);
n = next();
}
return sb.toString();
}
private boolean isWhiteSpace(int n) {
return n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1;
}
private boolean isEndOfLine(int n) {
return n == '\n' || n == '\r' || n == -1;
}
public void print(Object obj) {
pw.print(obj);
}
public void println(Object... obj) {
if(obj.length == 1)
pw.println(obj[0]);
else {
for(Object o: obj)
pw.print(o + " ");
pw.println();
}
}
public void flush() throws IOException {
pw.flush();
}
public void close() throws IOException {
pw.close();
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Tono loves to do shopping. Today, she went to the market where there are N different types of products. She wants to buy exactly K of them at the minimum cost. Although she is super smart, she wants to check your smartness as well. Can you tell her the minimum cost required to buy exactly K products if she has already decided to buy product J?
<b>Note:</b> Tono does not buy the same product twice, and Tono will definitely buy product J (J is the <b>index</b> of the item).The first line of the input contains three integers, N, K, and J, denoting the number of products in the market, the number of products Tono needs to buy, and the product that Tono will definitely buy.
The next line contains N singly spaced integers, the cost of the N products C[1], C[2], ..., C[N].
<b>Constraints:</b>
1 <= N <= 200000
1 <= K <= N
1 <= J <= N
1 <= C[i] <= 1000
Output a single integer, the minimum amount Tono needs to pay.Sample Input 1:
5 3 4
1 2 3 4 5
Sample Output 1:
7
Sample Input 2:
5 1 3
2 4 3 1 1
Sample Output 2:
3
<b>Explanation:</b>
Tono needs to buy exactly 3 products, and she will definitely buy the 4th product. Thus, she will buy the 1st, 2nd, and the 4th product. The total cost she pays is 1+2+4=7.
, I have written this Solution Code:
a=input().split()
b=input().split()
for j in [a,b]:
for i in range(0,len(j)):
j[i]=int(j[i])
n,k,j=a[0],a[1],a[2]
c_j=b[j-1]
b.sort()
if b[k-1]<=c_j:
b[k-1]=c_j
sum=0
for i in range(0,k):
sum+=b[i]
print(sum), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Tono loves to do shopping. Today, she went to the market where there are N different types of products. She wants to buy exactly K of them at the minimum cost. Although she is super smart, she wants to check your smartness as well. Can you tell her the minimum cost required to buy exactly K products if she has already decided to buy product J?
<b>Note:</b> Tono does not buy the same product twice, and Tono will definitely buy product J (J is the <b>index</b> of the item).The first line of the input contains three integers, N, K, and J, denoting the number of products in the market, the number of products Tono needs to buy, and the product that Tono will definitely buy.
The next line contains N singly spaced integers, the cost of the N products C[1], C[2], ..., C[N].
<b>Constraints:</b>
1 <= N <= 200000
1 <= K <= N
1 <= J <= N
1 <= C[i] <= 1000
Output a single integer, the minimum amount Tono needs to pay.Sample Input 1:
5 3 4
1 2 3 4 5
Sample Output 1:
7
Sample Input 2:
5 1 3
2 4 3 1 1
Sample Output 2:
3
<b>Explanation:</b>
Tono needs to buy exactly 3 products, and she will definitely buy the 4th product. Thus, she will buy the 1st, 2nd, and the 4th product. The total cost she pays is 1+2+4=7.
, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
#define sd(x) scanf("%d", &x)
#define sz(v) (int) v.size()
#define pr(v) For(i, 0, sz(v)) {cout<<v[i]<<" ";} cout<<endl;
#define slld(x) scanf("%lld", &x)
#define all(x) x.begin(), x.end()
#define For(i, st, en) for(int i=st; i<en; i++)
#define tr(x) for(auto it=x.begin(); it!=x.end(); it++)
#define fast std::ios::sync_with_stdio(false);cin.tie(NULL);
#define pb push_back
#define ll long long
#define ld long double
#define int long long
#define double long double
#define mp make_pair
#define F first
#define S second
typedef pair<int, int> pii;
typedef vector<int> vi;
#define pi 3.141592653589793238
const int MOD = 1e9+7;
const int INF = 1LL<<60;
const int N = 2e5+5;
// it's swapnil07 ;)
#ifdef SWAPNIL07
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void __f(const char* name, Arg1&& arg1){
cout << name << " : " << arg1 << endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args){
const char* comma = strchr(names + 1, ',');cout.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...);
}
int begtime = clock();
#define end_routine() cout << "\n\nTime elapsed: " << (clock() - begtime)*1000/CLOCKS_PER_SEC << " ms\n\n";
#else
#define endl '\n'
#define trace(...)
#define end_routine()
#endif
void solve(){
int n, k, j; cin>>n>>k>>j;
vector<int> vect;
int ans = 0;
For(i, 1, n+1){
int a; cin>>a;
if(i!=j)
vect.pb(a);
else
ans += a;
}
sort(all(vect));
for(int i=0; i<k-1; i++){
ans += vect[i];
}
cout<<ans;
}
signed main()
{
fast
#ifdef SWAPNIL07
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int t=1;
// cin>>t;
while(t--){
solve();
cout<<"\n";
}
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given an array Arr of N integers. A subarray is good if the sum of elements of that subarray is greater than or equal to K. Print the length of good subarray of minimum length.First line of input contains N and K.
Second line of input contains N integers representing the elements of the array Arr.
Constraints
1 <= N <= 100000
1 <= Arr[i] <= 100000
1 <= K <= 1000000000000Print the length of good subarray of minimum length.Sample input
5 12
2 3 2 5 5
Sample output
3
Explanation :
Subarray from index 3 to 5 has sum 12 and is therefore good and its length(3) is minimum among all possible good subarray., I have written this Solution Code: #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define VV vector
#define pb push_back
#define bitc __builtin_popcountll
#define m_p make_pair
#define infi 1e18+1
#define eps 0.000000000001
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);
string char_to_str(char c){string tem(1,c);return tem;}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<class T>//usage rand<long long>()
T rand() {
return uniform_int_distribution<T>()(rng);
}
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> oset;
// string to integer stoi()
// string to long long stoll()
// string.substr(position,length);
// integer to string to_string();
//////////////
auto clk=clock();
#define all(x) x.begin(),x.end()
#define S second
#define F first
#define sz(x) ((long long)x.size())
#define int long long
#define f80 __float128
#define pii pair<int,int>
/////////////
signed main()
{
fastio;
#ifdef ANIKET_GOYAL
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
int n;
cin>>n;
int k;
cin>>k;
int a[n+1];
int to=0;
for(int i=1;i<=n;++i)
{
cin>>a[i];
}
int j=1;
int s=0;
int ans=n;
for(int i=1;i<=n;++i)
{
while(s<k&&j<=n)
{
s+=a[j];
++j;
}
if(s>=k)
{
ans=min(ans,j-i);
}
s-=a[i];
}
cout<<ans;
#ifdef ANIKET_GOYAL
// cout<<endl<<endl<<endl<<endl<<"Time elapsed: "<<(double)(clock()-clk)/CLOCKS_PER_SEC<<endl;
#endif
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given an array Arr of N integers. A subarray is good if the sum of elements of that subarray is greater than or equal to K. Print the length of good subarray of minimum length.First line of input contains N and K.
Second line of input contains N integers representing the elements of the array Arr.
Constraints
1 <= N <= 100000
1 <= Arr[i] <= 100000
1 <= K <= 1000000000000Print the length of good subarray of minimum length.Sample input
5 12
2 3 2 5 5
Sample output
3
Explanation :
Subarray from index 3 to 5 has sum 12 and is therefore good and its length(3) is minimum among all possible good subarray., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s[]=br.readLine().split(" ");
int n=Integer.parseInt(s[0]);
long k=Long.parseLong(s[1]);
int a[]=new int[n];
s=br.readLine().split(" ");
for(int i=0;i<n;i++)
{
a[i]=Integer.parseInt(s[i]);
}
int length=Integer.MAX_VALUE,i=0,j=0;
long currSum=0;
for(j=0;j<n;j++)
{
currSum+=a[j];
while(currSum>=k)
{
length=Math.min(length,j-i+1);
currSum-=a[i];
i++;
}
}
System.out.println(length);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given an array Arr of N integers. A subarray is good if the sum of elements of that subarray is greater than or equal to K. Print the length of good subarray of minimum length.First line of input contains N and K.
Second line of input contains N integers representing the elements of the array Arr.
Constraints
1 <= N <= 100000
1 <= Arr[i] <= 100000
1 <= K <= 1000000000000Print the length of good subarray of minimum length.Sample input
5 12
2 3 2 5 5
Sample output
3
Explanation :
Subarray from index 3 to 5 has sum 12 and is therefore good and its length(3) is minimum among all possible good subarray., I have written this Solution Code: def result(arr,n,k):
minnumber = n + 1
start = 0
end = 0
curr_sum = 0
while(end < n):
while(curr_sum < k and end < n):
curr_sum += arr[end]
end += 1
while( curr_sum >= k and start < n):
if (end - start < minnumber):
minnumber = end - start
curr_sum -= arr[start]
start += 1
return minnumber
n = list(map(int, input().split()))
arr = list(map(int, input().split()))
print(result(arr, n[0], n[1])), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Implement <code>getObjKeys</code> which only takes one argument which will be a object.
The function should return all they keys present in object as a string where elements are seperated by a ', '. (No nested objects)(Use JS Built in function)Function will take one argument which will be an objectFunction will is string which contain all the keys from the input object seperated by a ', 'const obj = {email:"akshat. sethi@newtonschool. co", password:"123456"}
const keyString = getObjKeys(obj)
console. log(keyString) // prints email, password, I have written this Solution Code: function getObjKeys(obj){
return Object.keys(obj).join(",")
}, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Insertion is a basic but frequently used operation. Arrays in most languages cannnot be dynamically shrinked or expanded. Here, we will work with such arrays and try to insert an element at the end of array.
You are given an array arr. The size of the array is N. You need to insert an element at its end and print this newly modified array.The first line of input contains T denoting the number of testcases.
T testcases follow. Each testcase contains two lines of input.
The first line contains size of the array denoted by N and element to be inserted.
The third line contains N elements separated by spaces.
Constraints:
1 <= T <= 20
2 <= N <= 10000
0 <= element, arri <= 10^6For each testcase, in a new line, print the modified array.Input:
2
5 90
1 2 3 4 5
3 50
1 2 3
Output:
1 2 3 4 5 90
1 2 3 50
Explanation:
Testcase 1: After inserting 90 at end, we have array elements as 1 2 3 4 5 90.
Testcase 2: After inserting 50 at end, we have array elements as 1 2 3 50., I have written this Solution Code: #include<bits/stdc++.h>
using namespace std;
int main() {
int t;
cin>>t;
while(t--) {
long int n, el;
cin>>n>>el;
long int arr[n+1];
for(long int i=0; i<n; i++) {
cin>>arr[i];
}
arr[n] = el;
for(long int i=0; i<=n; i++) {
cout<<arr[i];
if (i != n) {
cout<<" ";
}
else if(t != 0) {
cout<<endl;
}
}
}
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Insertion is a basic but frequently used operation. Arrays in most languages cannnot be dynamically shrinked or expanded. Here, we will work with such arrays and try to insert an element at the end of array.
You are given an array arr. The size of the array is N. You need to insert an element at its end and print this newly modified array.The first line of input contains T denoting the number of testcases.
T testcases follow. Each testcase contains two lines of input.
The first line contains size of the array denoted by N and element to be inserted.
The third line contains N elements separated by spaces.
Constraints:
1 <= T <= 20
2 <= N <= 10000
0 <= element, arri <= 10^6For each testcase, in a new line, print the modified array.Input:
2
5 90
1 2 3 4 5
3 50
1 2 3
Output:
1 2 3 4 5 90
1 2 3 50
Explanation:
Testcase 1: After inserting 90 at end, we have array elements as 1 2 3 4 5 90.
Testcase 2: After inserting 50 at end, we have array elements as 1 2 3 50., I have written this Solution Code: t=int(input())
while t>0:
t-=1
li = list(map(int,input().strip().split()))
n=li[0]
num=li[1]
a= list(map(int,input().strip().split()))
a.insert(len(a),num)
for i in a:
print(i,end=" ")
print(), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Insertion is a basic but frequently used operation. Arrays in most languages cannnot be dynamically shrinked or expanded. Here, we will work with such arrays and try to insert an element at the end of array.
You are given an array arr. The size of the array is N. You need to insert an element at its end and print this newly modified array.The first line of input contains T denoting the number of testcases.
T testcases follow. Each testcase contains two lines of input.
The first line contains size of the array denoted by N and element to be inserted.
The third line contains N elements separated by spaces.
Constraints:
1 <= T <= 20
2 <= N <= 10000
0 <= element, arri <= 10^6For each testcase, in a new line, print the modified array.Input:
2
5 90
1 2 3 4 5
3 50
1 2 3
Output:
1 2 3 4 5 90
1 2 3 50
Explanation:
Testcase 1: After inserting 90 at end, we have array elements as 1 2 3 4 5 90.
Testcase 2: After inserting 50 at end, we have array elements as 1 2 3 50., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args)throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n =Integer.parseInt(br.readLine().trim());
while(n-->0){
String str[]=br.readLine().trim().split(" ");
String newel =br.readLine().trim()+" "+str[1];
System.out.println(newel);
}
}
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a sorted array <b>arr[]</b> of size <b>N</b> without duplicates, and given a value <b>x</b>. Find the floor of x in given array. Floor of x is defined as the largest element K in arr[] such that K is smaller than or equal to x.
Try to use binary search to solve this problem.First line of input contains number of testcases T. For each testcase, first line of input contains number of elements in the array and element whose floor is to be searched. Last line of input contains array elements.
<b>Constraints:</b>
1 ≤ T ≤ 100
1 ≤ N ≤ 10^5
1 ≤ arr[i] ≤ 10^18
0 ≤ X ≤ arr[n-1]Output the index of floor of x if exists, else print -1. Use 0-indexingInput:
3
7 0
1 2 8 10 11 12 19
7 5
1 2 8 10 11 12 19
7 10
1 2 8 10 11 12 19
Output:
-1
1
3
Explanation:
Testcase 1: No element less than or equal to 0 is found. So output is "-1".
Testcase 2: Number less than or equal to 5 is 2, whose index is 1(0-based indexing).
Testcase 3: Number less than or equal to 10 is 10 and its index is 3., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static int BS(int arr[],int x,int start,int end){
if( start > end) return start-1;
int mid = start + (end - start)/2;
if(arr[mid]==x) return mid;
if(arr[mid]>x) return BS(arr,x,start,mid-1);
return BS(arr,x,mid+1,end);
}
public static void main (String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
String[] s;
for(;t>0;t--){
s = br.readLine().split(" ");
int n = Integer.parseInt(s[0]);
int x = Integer.parseInt(s[1]);
s = br.readLine().split(" ");
int[] arr = new int[n];
for(int i=0;i<n;i++)
arr[i] = Integer.parseInt(s[i]);
int res = BS(arr,x,0,arr.length-1);
System.out.println(res);
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a sorted array <b>arr[]</b> of size <b>N</b> without duplicates, and given a value <b>x</b>. Find the floor of x in given array. Floor of x is defined as the largest element K in arr[] such that K is smaller than or equal to x.
Try to use binary search to solve this problem.First line of input contains number of testcases T. For each testcase, first line of input contains number of elements in the array and element whose floor is to be searched. Last line of input contains array elements.
<b>Constraints:</b>
1 ≤ T ≤ 100
1 ≤ N ≤ 10^5
1 ≤ arr[i] ≤ 10^18
0 ≤ X ≤ arr[n-1]Output the index of floor of x if exists, else print -1. Use 0-indexingInput:
3
7 0
1 2 8 10 11 12 19
7 5
1 2 8 10 11 12 19
7 10
1 2 8 10 11 12 19
Output:
-1
1
3
Explanation:
Testcase 1: No element less than or equal to 0 is found. So output is "-1".
Testcase 2: Number less than or equal to 5 is 2, whose index is 1(0-based indexing).
Testcase 3: Number less than or equal to 10 is 10 and its index is 3., I have written this Solution Code: def bsearch(arr,e,l,r):
if(r>=l):
mid = l + (r - l)//2
if (arr[mid] == e):
return mid
elif arr[mid] > e:
return bsearch(arr, e,l, mid-1)
else:
return bsearch(arr,e, mid + 1, r)
else:
return r
t=int(input())
for i in range(t):
ip=list(map(int,input().split()))
l=list(map(int,input().split()))
le=ip[0]
e=ip[1]
print(bsearch(sorted(l),e,0,le-1)), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a sorted array <b>arr[]</b> of size <b>N</b> without duplicates, and given a value <b>x</b>. Find the floor of x in given array. Floor of x is defined as the largest element K in arr[] such that K is smaller than or equal to x.
Try to use binary search to solve this problem.First line of input contains number of testcases T. For each testcase, first line of input contains number of elements in the array and element whose floor is to be searched. Last line of input contains array elements.
<b>Constraints:</b>
1 ≤ T ≤ 100
1 ≤ N ≤ 10^5
1 ≤ arr[i] ≤ 10^18
0 ≤ X ≤ arr[n-1]Output the index of floor of x if exists, else print -1. Use 0-indexingInput:
3
7 0
1 2 8 10 11 12 19
7 5
1 2 8 10 11 12 19
7 10
1 2 8 10 11 12 19
Output:
-1
1
3
Explanation:
Testcase 1: No element less than or equal to 0 is found. So output is "-1".
Testcase 2: Number less than or equal to 5 is 2, whose index is 1(0-based indexing).
Testcase 3: Number less than or equal to 10 is 10 and its index is 3., I have written this Solution Code: #include "bits/stdc++.h"
#pragma GCC optimize "03"
using namespace std;
#define int long long int
#define ld long double
#define pi pair<int, int>
#define pb push_back
#define fi first
#define se second
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#ifndef LOCAL
#define endl '\n'
#endif
const int N = 2e5 + 5;
const int mod = 1e9 + 7;
const int inf = 1e9 + 9;
int a[N];
signed main() {
IOS;
int t; cin >> t;
while(t--){
int n, x; cin >> n >> x;
for(int i = 0; i < n; i++)
cin >> a[i];
int l = -1, h = n;
while(l+1 < h){
int m = (l + h) >> 1;
if(a[m] <= x)
l = m;
else
h = m;
}
cout << l << endl;
}
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a dictionary, a method to do lookup in dictionary and a M x N board where every cell has one character. Find all possible words that can be formed by a sequence of adjacent characters. Note that we can move to any of 8 adjacent characters, but a word should not have multiple instances of same cell.
Example:
Input: dictionary[] = {"GEEKS", "FOR", "QUIZ", "GO"};
boggle[][] = {{'G','I','Z'}, {'U','E','K'}, {'Q','S','E'}};
Output: Following words of the dictionary are present
GEEKS, QUIZFirst line contains an integer X denoting the no of words in the dictionary. Then in the next line are X space separated strings denoting the contents of the dictionary. In the next line are two integers N and M denoting the size of the boggle. Next N lines each contains M characters denoting the contents of the boggle.
Constraints:
1 < = X < = 10
1 < = N, M < = 4
1 < = |String| < = 10
All input strings are made up of uppercase characters of the English alphabets.Print in a single line and in a sorted order all the words of the dictionary which could be formed from the boggle. If no word can be formed print -1.Sample Input:
4
GEEKS FOR QUIZ GO
3 3
G I Z
U E K
Q S E
Sample Output:
GEEKS QUIZ, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String str1 = br.readLine();
String[] str2 = str1.split(" ");
String str3 = br.readLine();
String[] str4 = str3.split(" ");
int row = Integer.parseInt(str4[0]);
int col = Integer.parseInt(str4[1]);
char[][] cha = new char[row][col];
for(int i = 0; i < row; ++i) {
String str5 = br.readLine();
String[] str6 = str5.split(" ");
for(int j = 0; j < col; ++j) {
cha[i][j] = str6[j].charAt(0);
}
}
List<String> list = new ArrayList<>();
for(int i = 0; i < n; ++i) {
if(solve(cha,str2[i])) {
list.add(str2[i]);
}
}
if(list.size() == 0) {
System.out.print(-1);
} else {
Collections.sort(list);
for(String i : list) System.out.print(i+" ");
}
}
static boolean solve(char[][] arr,String str) {
for(int i = 0; i < arr.length; ++i) {
for(int j = 0; j < arr[0].length; ++j) {
if(helper(arr, str, i, j, 0)) {
return true;
}
}
}
return false;
}
static boolean helper(char[][] arr, String str, int i, int j, int index) {
if(index >= str.length()) return true;
if(i < 0 || j < 0 || i > arr.length-1 || j > arr[0].length-1 || arr[i][j] != str.charAt(index)) {
return false;
}
char temp = arr[i][j];
arr[i][j] = '#';
if(helper(arr, str, i-1, j, index+1) || helper(arr, str, i-1, j+1, index+1) ||
helper(arr, str, i, j+1, index+1) || helper(arr, str, i+1,j+1, index+1) || helper(arr,str,i+1,j,index+1) ||
helper (arr, str, i+1, j-1, index+1) || helper(arr, str, i, j-1, index+1) ||
helper(arr, str, i-1, j-1, index+1)) {
arr[i][j] = temp;
return true;
}
arr[i][j] = temp;
return false;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a dictionary, a method to do lookup in dictionary and a M x N board where every cell has one character. Find all possible words that can be formed by a sequence of adjacent characters. Note that we can move to any of 8 adjacent characters, but a word should not have multiple instances of same cell.
Example:
Input: dictionary[] = {"GEEKS", "FOR", "QUIZ", "GO"};
boggle[][] = {{'G','I','Z'}, {'U','E','K'}, {'Q','S','E'}};
Output: Following words of the dictionary are present
GEEKS, QUIZFirst line contains an integer X denoting the no of words in the dictionary. Then in the next line are X space separated strings denoting the contents of the dictionary. In the next line are two integers N and M denoting the size of the boggle. Next N lines each contains M characters denoting the contents of the boggle.
Constraints:
1 < = X < = 10
1 < = N, M < = 4
1 < = |String| < = 10
All input strings are made up of uppercase characters of the English alphabets.Print in a single line and in a sorted order all the words of the dictionary which could be formed from the boggle. If no word can be formed print -1.Sample Input:
4
GEEKS FOR QUIZ GO
3 3
G I Z
U E K
Q S E
Sample Output:
GEEKS QUIZ, I have written this Solution Code: // C++ program for Boggle game
#include <bits/stdc++.h>
using namespace std;
// Let the given dictionary be following
string dictionary[100];
int n;
int M, N;
bool flag;
set<string> res;
bool isWord(string& str)
{
// Linearly search all words
for (int i = 0; i < n; i++)
if (str.compare(dictionary[i]) == 0)
return true;
return false;
}
// A recursive function to print all words present on boggle
void findWordsUtil(vector<vector<char> > boggle, vector<vector<bool> > visited, int i,
int j, string& str)
{
// Mark current cell as visited and append current character
// to str
visited[i][j] = true;
str = str + boggle[i][j];
// If str is present in dictionary, then print it
if (isWord(str)) {
res.insert(str);
}
// Traverse 8 adjacent cells of boggle[i][j]
for (int row = i - 1; row <= i + 1 && row < M; row++)
for (int col = j - 1; col <= j + 1 && col < N; col++)
if (row >= 0 && col >= 0 && !visited[row][col])
findWordsUtil(boggle, visited, row, col, str);
// Erase current character from string and mark visited
// of current cell as false
str.erase(str.length() - 1);
visited[i][j] = false;
}
// Prints all words present in dictionary.
void findWords(vector<vector<char> > boggle)
{
// Mark all characters as not visited
vector<vector<bool> > visited(M, vector<bool>(N, 0));
// Initialize current string
string str = "";
// Consider every character and look for all words
// starting with this character
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
findWordsUtil(boggle, visited, i, j, str);
}
// Driver program to test above function
int main()
{
cin >> n;
for(int i = 0; i < n; i++)
cin >> dictionary[i];
sort(dictionary, dictionary + n);
cin >> M >> N;
vector<vector<char> > boggle(M, vector<char>(N, '\0'));
for(int i = 0; i < M; i++)
for(int j = 0; j < N; j++)
cin >> boggle[i][j];
findWords(boggle);
if(res.size() == 0)
cout << -1 << endl;
else{
for(auto i: res)
cout << i << " ";
}
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer K and an array height[] of size N, where height[i] denotes the height of the ith tree in a forest. The task is to make a cut of height X from the ground such that at max K units wood is collected. Find the minimum value of X
<b>If you make a cut of height X from the ground then every tree with a height greater than X will be reduced to X and the remaining part of the wood can be collected</b>The first line contains two integers N and K.
The next line contains N integers denoting the elements of the array height[]
<b>Constraints</b>
1 ≤ N ≤ 10<sup>5</sup>
1 ≤ arr[i] ≤ 10<sup>5</sup>
1 ≤ K ≤ 10<sup>7</sup>Print a single integer with the value of X.Sample Input:
4 2
1 2 1 2
Sample Output:
1
<b>Explanation:</b>
Make a cut at height 1, the updated array will be {1, 1, 1, 1} and
the collected wood will be {0, 1, 0, 1} i. e. 0 + 1 + 0 + 1 = 2., I have written this Solution Code: import java.io.*; // for handling input/output
import java.util.*; // contains Collections framework
// don't change the name of this class
// you can add inner classes if needed
class Main {
public static void main (String[] args) {
// Your code here
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int arr[] = new int[n];
for(int i = 0; i < n; i++)
arr[i] = sc.nextInt();
System.out.println(minValue(arr, n, k));
}
static int minValue(int arr[], int N, int k)
{
int l = 0, h = N;
while(l+1 < h){
int m = (l + h) >> 1;
if(f(arr, m, N) <= k)
h = m;
else
l = m;
}
return h;
}
static int f(int a[], int x, int n)
{
int sum = 0;
for(int i = 0; i < n; i++)
sum += Math.max(a[i]-x, 0);
return sum;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer K and an array height[] of size N, where height[i] denotes the height of the ith tree in a forest. The task is to make a cut of height X from the ground such that at max K units wood is collected. Find the minimum value of X
<b>If you make a cut of height X from the ground then every tree with a height greater than X will be reduced to X and the remaining part of the wood can be collected</b>The first line contains two integers N and K.
The next line contains N integers denoting the elements of the array height[]
<b>Constraints</b>
1 ≤ N ≤ 10<sup>5</sup>
1 ≤ arr[i] ≤ 10<sup>5</sup>
1 ≤ K ≤ 10<sup>7</sup>Print a single integer with the value of X.Sample Input:
4 2
1 2 1 2
Sample Output:
1
<b>Explanation:</b>
Make a cut at height 1, the updated array will be {1, 1, 1, 1} and
the collected wood will be {0, 1, 0, 1} i. e. 0 + 1 + 0 + 1 = 2., I have written this Solution Code: def minCut(arr,k):
mini = 1
maxi = k
mid = 0
while mini<=maxi:
mid = mini + int((maxi - mini)/2)
wood = 0
for j in range(n):
if(arr[j]-mid>=0):
wood += arr[j] - mid
if wood == k:
break;
elif wood > k:
mini = mid+1
else:
maxi = mid-1
print(mini)
n,k = list(map(int, input().split()))
arr = list(map(int, input().split()))
minCut(arr,k), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer K and an array height[] of size N, where height[i] denotes the height of the ith tree in a forest. The task is to make a cut of height X from the ground such that at max K units wood is collected. Find the minimum value of X
<b>If you make a cut of height X from the ground then every tree with a height greater than X will be reduced to X and the remaining part of the wood can be collected</b>The first line contains two integers N and K.
The next line contains N integers denoting the elements of the array height[]
<b>Constraints</b>
1 ≤ N ≤ 10<sup>5</sup>
1 ≤ arr[i] ≤ 10<sup>5</sup>
1 ≤ K ≤ 10<sup>7</sup>Print a single integer with the value of X.Sample Input:
4 2
1 2 1 2
Sample Output:
1
<b>Explanation:</b>
Make a cut at height 1, the updated array will be {1, 1, 1, 1} and
the collected wood will be {0, 1, 0, 1} i. e. 0 + 1 + 0 + 1 = 2., I have written this Solution Code: #include "bits/stdc++.h"
using namespace std;
#define ll long long int
#define ld long double
#define pi pair<int, int>
#define pb push_back
#define fi first
#define se second
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#ifndef LOCAL
#define endl '\n'
#endif
const int N = 1e5 + 5;
const int mod = 1e9 + 7;
const int inf = 1e9 + 9;
int a[N], n, k;
int f(int x){
int sum = 0;
for(int i = 1; i <= n; i++)
sum += max(a[i]-x, 0);
return sum;
}
void solve(){
cin >> n >> k;
for(int i = 1; i <= n; i++)
cin >> a[i];
int l = 0, h = N;
while(l+1 < h){
int m = (l + h) >> 1;
if(f(m) <= k)
h = m;
else
l = m;
}
cout << h;
}
void testcases(){
int tt = 1;
//cin >> tt;
while(tt--){
solve();
}
}
signed main() {
IOS;
testcases();
return 0;
} , In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Solo likes to solve simple problems, but this time she is stuck with an easy problem she created herself. Since she cannot visit her friends currently (neither should you), can you code this problem for her? The problem is short and sweet.
Given an integer n, can you find the smallest n-digit number that is divisible by both 3 and 7? (Of course, the number cannot begin with a 0)The only line of input contains a single integer n, the number of digits in the required number.
Constraints
2 <= n <= 100000Output a single integer, the required n digit number. (The answer may not fit into 32 or 64 bit data types).Sample Input 1
2
Sample Output 1
21
Sample Input 2
4
Sample Output
1008
Explanation 1: 21 is the first 2 digit number divisible by both 3 and 7., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args)throws IOException {
BufferedReader rdr = new BufferedReader(new InputStreamReader(System.in));
long n = Long.parseLong(rdr.readLine());
if(n==0 || n==1){
return ;
}
if(n==2){
System.out.println(21);
}
else{
StringBuilder str= new StringBuilder();
str.append("1");
for(long i=0;i<n-3;i++){
str.append("0");
}
if(n%6==0){
str.append("02");
System.out.println(str.toString());
}
else if(n%6==1){
str.append("20");
System.out.println(str.toString());
}
else if(n%6==2){
str.append("11");
System.out.println(str.toString());
}
else if(n%6==3){
str.append("05");
System.out.println(str.toString());
}
if(n%6==4){
str.append("08");
System.out.println(str.toString());
return;
}
else if(n%6==5){
str.append("17");
System.out.println(str.toString());
}
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Solo likes to solve simple problems, but this time she is stuck with an easy problem she created herself. Since she cannot visit her friends currently (neither should you), can you code this problem for her? The problem is short and sweet.
Given an integer n, can you find the smallest n-digit number that is divisible by both 3 and 7? (Of course, the number cannot begin with a 0)The only line of input contains a single integer n, the number of digits in the required number.
Constraints
2 <= n <= 100000Output a single integer, the required n digit number. (The answer may not fit into 32 or 64 bit data types).Sample Input 1
2
Sample Output 1
21
Sample Input 2
4
Sample Output
1008
Explanation 1: 21 is the first 2 digit number divisible by both 3 and 7., I have written this Solution Code: n = input()
n=int(n)
n1=10**(n-1)
n2=10**(n)
while(n1<n2):
if((n1%3==0) and (n1%7==0)):
print(n1)
break
n1 = n1+1, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.