Instruction
stringlengths 261
35k
| Response
stringclasses 1
value |
---|---|
For this Question: You have a house, which you model as an axis-aligned rectangle with corners at (x1, y1) and (x2, y2).
You also have a goat, which you want to tie to a fence post located at (x, y), with a rope of length
l. The goat can reach anywhere within a distance l from the fence post.
Find the largest value of l so that the goat cannot reach your house.Input consists of a single line with six space-separated integers x, y, x1, y1, x2, and y2. All the
values are guaranteed to be between −1000 and 1000 (inclusive).
It is guaranteed that x1 < x2 and y1 < y2, and that (x, y) lies strictly outside the axis-aligned
rectangle with corners at (x1, y1) and (x2, y2).Print, on one line, the maximum value of l, rounded and displayed to exactly three decimal placessample input
7 4 0 0 5 4
sample output
2.000
sample input
6 0 0 2 7 6
sample output
2.000
sample input
4 8 7 8 9 9
sample output
3.000, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
static double distance(int x,int y,int x1,int y1)
{
return Math.sqrt(((x-x1)*(x-x1))+((y-y1)*(y-y1)));
}
public static void main (String[] args) throws IOException{
BufferedReader scan=new BufferedReader(new InputStreamReader(System.in));
String s[]=scan.readLine().split(" ");
int x=Integer.parseInt(s[0]);
int y=Integer.parseInt(s[1]);
int x1=Integer.parseInt(s[2]);
int y1=Integer.parseInt(s[3]);
int x2=Integer.parseInt(s[4]);
int y2=Integer.parseInt(s[5]);
double ans=0.0;
if(x>=x1&&x<=x2)
{
ans=Math.min(Math.abs(y-y1),Math.abs(y-y2));
}
else if(y>=y1&&y<=y2)
{
ans=Math.min(Math.abs(x-x1),Math.abs(x-x2));
}
else
{
ans=distance(x,y,x1,y1);
ans=Math.min(ans,distance(x,y,x2,y2));
ans=Math.min(ans,distance(x,y,x1,y2));
ans=Math.min(ans,distance(x,y,x2,y1));
}
System.out.printf("%.3f",ans);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You have a house, which you model as an axis-aligned rectangle with corners at (x1, y1) and (x2, y2).
You also have a goat, which you want to tie to a fence post located at (x, y), with a rope of length
l. The goat can reach anywhere within a distance l from the fence post.
Find the largest value of l so that the goat cannot reach your house.Input consists of a single line with six space-separated integers x, y, x1, y1, x2, and y2. All the
values are guaranteed to be between −1000 and 1000 (inclusive).
It is guaranteed that x1 < x2 and y1 < y2, and that (x, y) lies strictly outside the axis-aligned
rectangle with corners at (x1, y1) and (x2, y2).Print, on one line, the maximum value of l, rounded and displayed to exactly three decimal placessample input
7 4 0 0 5 4
sample output
2.000
sample input
6 0 0 2 7 6
sample output
2.000
sample input
4 8 7 8 9 9
sample output
3.000, I have written this Solution Code: import math
x,y,x1,y1,x2,y2=map(int,input().split())
ans=0
coord=[]
if(x>=x1 and x<=x2):
ans=min(abs(y-y1),abs(y-y2))
elif (y>=y1 and y<=y2):
ans=min(abs(x-x1),abs(x-x2))
else:
ans=min( math.sqrt(abs(x-x1)**2 + abs(y-y1)**2), math.sqrt(abs(x-x2)**2 +abs(y-y2)**2), math.sqrt(abs(x-x1)**2 +abs(y-y2)**2), math.sqrt(abs(x-x2)**2+abs(y-y1)**2))
print("%.3f"%ans)
'''x,y,x1,y1,x2,y2=map(int,input().split())
ans=0
coord=[]
coord.append([x1,y1])
coord.append([x2,y2])
coord.append([x1,y1+y2])
coord.append([x1+x2,y1])
f=[]
f.append(math.sqrt((x1-x)*(x1-x) + (y1-y)*(y1-y)))
f.append(math.sqrt((x2-x)*(x2-x) + (y2-y)*(y2-y)))
f.append(math.sqrt((x1-x)*(x1-x) + (y1+y2-y)*(y1+y2-y)))
f.append(math.sqrt((x1+x2-x)*(x1+x2-x) + (y1-y)*(y1-y)))
needed=coord[f.index(min(f))]
possCoord=[[needed[0],y],[x,needed[1]]]
for i in possCoord:
if x1<=i[0] and i[0]<=x2 and y1<=i[1] and i[1]<=y2:
ans=round(math.sqrt((i[0]-x)*(i[0]-x) + (i[1]-y)*(i[1]-y)),3)
print("%.3f"%ans)''', In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You have a house, which you model as an axis-aligned rectangle with corners at (x1, y1) and (x2, y2).
You also have a goat, which you want to tie to a fence post located at (x, y), with a rope of length
l. The goat can reach anywhere within a distance l from the fence post.
Find the largest value of l so that the goat cannot reach your house.Input consists of a single line with six space-separated integers x, y, x1, y1, x2, and y2. All the
values are guaranteed to be between −1000 and 1000 (inclusive).
It is guaranteed that x1 < x2 and y1 < y2, and that (x, y) lies strictly outside the axis-aligned
rectangle with corners at (x1, y1) and (x2, y2).Print, on one line, the maximum value of l, rounded and displayed to exactly three decimal placessample input
7 4 0 0 5 4
sample output
2.000
sample input
6 0 0 2 7 6
sample output
2.000
sample input
4 8 7 8 9 9
sample output
3.000, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
float dist(int x1, int y1, int x2, int y2)
{
return sqrt(pow(x2-x1,2) + pow(y2-y1,2));
}
int main()
{
int x, y, x1, y1, x2, y2;
cin >> x >> y >> x1 >> y1 >> x2 >> y2;
float d = dist(x,y,x1,y1);
d = min(d, dist(x,y,x1,y2));
d = min(d, dist(x,y,x2,y2));
d = min(d, dist(x,y,x2,y1));
if (x > x1 and x < x2)
{
d = min(d, dist(x,y,x,y1));
d = min(d, dist(x,y,x,y2));
}
if (y > y1 and y < y2)
{
d = min(d, dist(x,y,x1,y));
d = min(d, dist(x,y,x2,y));
}
printf("%.3f", d);
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 and Q queries. Your task is to perform these operations:-
enqueue: this operation will add an element to your current queue.
dequeue: this operation will delete the element from the starting of the queue
displayfront: this operation will print the element presented at the frontUser task:
Since this will be a functional problem, you don't have to take input. You just have to complete the functions:
<b>enqueue()</b>:- that takes the integer to be added and the maximum size of array as parameter.
<b>dequeue()</b>:- that takes the queue as parameter.
<b>displayfront()</b> :- that takes the queue as parameter.
Constraints:
1 <= Q(Number of queries) <= 10<sup>3</sup>
<b> Custom Input:</b>
First line of input should contains two integer number of queries Q and the size of the array N. Next Q lines contains any of the given three operations:-
enqueue x
dequeue
displayfrontDuring a dequeue operation if queue is empty you need to print "Queue is empty", during enqueue operation if the maximum size of array is reached you need to print "Queue is full" and during displayfront operation you need to print the element which is at the front and if the queue is empty you need to print "Queue is empty".
Note:-Each msg or element is to be printed on a new line
Sample Input:-
8 2
displayfront
enqueue 2
displayfront
enqueue 4
displayfront
dequeue
displayfront
enqueue 5
Sample Output:-
Queue is empty
2
2
4
Queue is full
Explanation:-here size of given array is 2 so when last enqueue operation perfomed the array was already full so we display the msg "Queue is full".
Sample input:
5 5
enqueue 4
enqueue 5
displayfront
dequeue
displayfront
Sample output:-
4
5, I have written this Solution Code: public static void enqueue(int x,int k)
{
if (rear >= k) {
System.out.println("Queue is full");
}
else {
a[rear] = x;
rear++;
}
}
public static void dequeue()
{
if (rear <= front) {
System.out.println("Queue is empty");
}
else {
front++;
}
}
public static void displayfront()
{
if (rear<=front) {
System.out.println("Queue is empty");
}
else {
int x = a[front];
System.out.println(x);
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a matrix of size M*N, your task is to find the column having the maximum sum and print the sum.The first line of input contains two space-separated integers M and N. The following M lines of input contain N space-separated integers each depicting the values of the matrix.
Constraints:-
1 <= M, N <= 100
1 <= Matrix[][] <= 100000Print the maximum sum.Sample Input:-
3 3
1 2 3
4 5 6
7 8 9
Sample Output:-
18
Explanation:-
1 + 4 + 7 = 12
2 + 5 + 8 = 15
3 + 6 + 9 = 18
maximum = 18
Sample Input:-
3 2
1 4
9 6
9 1
Sample Output:-
19, I have written this Solution Code: m,n=map(int ,input().split())
matrix=[]
for i in range(m):
l1=[eval(x) for x in input().split()]
matrix.append(l1)
l2=[]
for coloumn in range(n):
sum1=0
for row in range(m):
sum1+= matrix[row][coloumn]
l2.append(sum1)
print(max(l2))
'''for row in range(n):
sum2=0
for col in range(m):
sum2 += matrix[row][col]
print(sum2)''', In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a matrix of size M*N, your task is to find the column having the maximum sum and print the sum.The first line of input contains two space-separated integers M and N. The following M lines of input contain N space-separated integers each depicting the values of the matrix.
Constraints:-
1 <= M, N <= 100
1 <= Matrix[][] <= 100000Print the maximum sum.Sample Input:-
3 3
1 2 3
4 5 6
7 8 9
Sample Output:-
18
Explanation:-
1 + 4 + 7 = 12
2 + 5 + 8 = 15
3 + 6 + 9 = 18
maximum = 18
Sample Input:-
3 2
1 4
9 6
9 1
Sample Output:-
19, I have written this Solution Code: // mat is the matrix/ 2d array
// the dimensions of array are:- a rows, b columns
function colMaxSum(mat,a,b) {
// write code here
// do not console.log
// return the answer as a number
let idx = -1;
// Variable to store max sum
let maxSum = Number.MIN_VALUE;
// Traverse matrix column wise
for (let i = 0; i < b; i++) {
let sum = 0;
// calculate sum of column
for (let j = 0; j < a; j++) {
sum += mat[j][i];
}
// Update maxSum if it is
// less than current sum
if (sum > maxSum) {
maxSum = sum;
// store index
idx = i;
}
}
let res;
res = [idx, maxSum];
// return result
return maxSum;
}
, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a matrix of size M*N, your task is to find the column having the maximum sum and print the sum.The first line of input contains two space-separated integers M and N. The following M lines of input contain N space-separated integers each depicting the values of the matrix.
Constraints:-
1 <= M, N <= 100
1 <= Matrix[][] <= 100000Print the maximum sum.Sample Input:-
3 3
1 2 3
4 5 6
7 8 9
Sample Output:-
18
Explanation:-
1 + 4 + 7 = 12
2 + 5 + 8 = 15
3 + 6 + 9 = 18
maximum = 18
Sample Input:-
3 2
1 4
9 6
9 1
Sample Output:-
19, 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 1001
#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[m];
for(int i=0;i<m;i++){
a[i]=0;
}
int x;
int sum=0;
FOR(i,n){
FOR(j,m){
cin>>x;
a[j]+=x;
sum=max(sum,a[j]);
}
}
out(sum);
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a matrix of size M*N, your task is to find the column having the maximum sum and print the sum.The first line of input contains two space-separated integers M and N. The following M lines of input contain N space-separated integers each depicting the values of the matrix.
Constraints:-
1 <= M, N <= 100
1 <= Matrix[][] <= 100000Print the maximum sum.Sample Input:-
3 3
1 2 3
4 5 6
7 8 9
Sample Output:-
18
Explanation:-
1 + 4 + 7 = 12
2 + 5 + 8 = 15
3 + 6 + 9 = 18
maximum = 18
Sample Input:-
3 2
1 4
9 6
9 1
Sample Output:-
19, 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 m = sc.nextInt();
int n = sc.nextInt();
int a[][] = new int[m][n];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
a[i][j]=sc.nextInt();
}
}
int sum=0;
int ans=0;
for(int i=0;i<n;i++){
sum=0;
for(int j=0;j<m;j++){
sum+=a[j][i];
}
if(sum>ans){ans=sum;}
}
System.out.print(ans);
}
}
, 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, give the number with maximum frequency. If multiple numbers have maximum frequency print the maximum number among them.The first line of the input contains an integer N, and the Second line contains N space-separated integers of the array.
<b>Constraints:</b>
3 <= N <= 1000
1 <= Arr[i] <= 100The output should contain single integer, the number with maximum frequency.If multiple numbers have maximum frequency print the maximum number among them.Sample Input
5
1 4 2 4 5
Sample Output
4
<b>Explanation:-</b>
4 has max frequency=2, 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().trim().split(" ");
int a[]=new int[n];
for(int i=0;i<n;i++){
a[i]=Integer.parseInt(str[i]);
}
Arrays.sort(a);
int size=a[n-1]+1;
int c[]=new int[size];
for(int i=0;i<size;i++) c[i]=0;
for(int i=0;i<n;i++) c[a[i]]++;
int max=0,freq=c[1];
for(int i=2;i<size;i++){
if(freq<=c[i]){
freq=c[i];
max=i;
}
}
System.out.println(max);
}
}, 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, give the number with maximum frequency. If multiple numbers have maximum frequency print the maximum number among them.The first line of the input contains an integer N, and the Second line contains N space-separated integers of the array.
<b>Constraints:</b>
3 <= N <= 1000
1 <= Arr[i] <= 100The output should contain single integer, the number with maximum frequency.If multiple numbers have maximum frequency print the maximum number among them.Sample Input
5
1 4 2 4 5
Sample Output
4
<b>Explanation:-</b>
4 has max frequency=2, I have written this Solution Code: n = int(input())
a = [int(x) for x in input().split()]
freq = {}
for x in a:
if x not in freq:
freq[x] = 1
else:
freq[x] += 1
mx = max(freq.values())
rf = sorted(freq)
for i in range(len(rf) - 1, -1, -1):
if freq[rf[i]] == mx:
print(rf[i])
break, 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, give the number with maximum frequency. If multiple numbers have maximum frequency print the maximum number among them.The first line of the input contains an integer N, and the Second line contains N space-separated integers of the array.
<b>Constraints:</b>
3 <= N <= 1000
1 <= Arr[i] <= 100The output should contain single integer, the number with maximum frequency.If multiple numbers have maximum frequency print the maximum number among them.Sample Input
5
1 4 2 4 5
Sample Output
4
<b>Explanation:-</b>
4 has max frequency=2, 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 n; cin >> n;
for(int i = 1; i <= n; i++){
int p; cin >> p;
a[p]++;
}
int mx = 0, id = -1;
for(int i = 1; i <= 100; i++){
if(a[i] >= mx)
mx = a[i], id = i;
}
cout << id;
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Write a program to check whether a number is even or odd using switch case.First Line of the input contains the number n.
<b>Constraints</b>
1 <= n <= 1e9If the number is even print "Even" otherwise "Odd"Sample Input :
23
Sample Output :
Odd
Sample Input :
24
Sample Output :
Even, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) {
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t= Integer.parseInt(br.readLine());
if(t%2==0)
System.out.println("Even");
else
System.out.println("Odd");
}
catch (Exception e){
return;
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Write a program to check whether a number is even or odd using switch case.First Line of the input contains the number n.
<b>Constraints</b>
1 <= n <= 1e9If the number is even print "Even" otherwise "Odd"Sample Input :
23
Sample Output :
Odd
Sample Input :
24
Sample Output :
Even, I have written this Solution Code: n = int(input())
if n % 2 == 0:
print("Even")
else:
print("Odd"), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Write a program to check whether a number is even or odd using switch case.First Line of the input contains the number n.
<b>Constraints</b>
1 <= n <= 1e9If the number is even print "Even" otherwise "Odd"Sample Input :
23
Sample Output :
Odd
Sample Input :
24
Sample Output :
Even, I have written this Solution Code: #include <stdio.h>
int main()
{
int num;
scanf("%d", &num);
switch(num % 2)
{
case 0:
printf("Even");
break;
/* Else if n%2 == 1 */
case 1:
printf("Odd");
break;
}
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: They say friendship is greater than love. Why not play the famous game "FLAMES".
The rules are super simple. Given two strings (all lowercase), remove all the letters that are common to both the strings from both the strings. You cannot erase a character in first string whichever corresponding same character in other string not exist.
For example, in the case
String 1: saumya
String 2: ansh
You can remove only 1 'a' and 1 's' from both the strings.
Remaining strings are:
String 1: umya
String 2: nh
Now all you need to do is find the sum of the remaining strings length % 6.
Output:
If obtained value is 1, output "Friends"
If obtained value is 2, output "Love"
If obtained value is 3, output "Affection"
If obtained value is 4, output "Marriage"
If obtained value is 5, output "Enemy"
If obtained value is 0, output "Siblings"You will be given two strings on different lines.
Constraints
1 <= Length of both the strings <= 100000Output a single string, the result of FLAMES test.Sample Input:-
saumya
ansh
Sample Output:-
Siblings
Explanation:-
after deleting characters :-
str1 = umya
str2 = nh
sum = 4+2
sum%6=0
, 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 str1 = br.readLine();
String str2 = br.readLine();
countCommonCharacters(str1, str2);
}
static void countCommonCharacters(String s1, String s2) {
int[] arr1 = new int[26];
int[] arr2 = new int[26];
for (int i = 0; i < s1.length(); i++)
arr1[s1.codePointAt(i) - 97]++;
for (int i = 0; i < s2.length(); i++)
arr2[s2.codePointAt(i) - 97]++;
int lenToCut = 0;
for (int i = 0; i < 26; i++) {
int leastOccurrence = Math.min(arr1[i], arr2[i]);
lenToCut += (2 * leastOccurrence);
}
System.out.println(findRelation((s1.length() + s2.length() - lenToCut) % 6));
}
static String findRelation(int value) {
switch (value) {
case 1:
return "Friends";
case 2:
return "Love";
case 3:
return "Affection";
case 4:
return "Marriage";
case 5:
return "Enemy";
default:
return "Siblings";
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: They say friendship is greater than love. Why not play the famous game "FLAMES".
The rules are super simple. Given two strings (all lowercase), remove all the letters that are common to both the strings from both the strings. You cannot erase a character in first string whichever corresponding same character in other string not exist.
For example, in the case
String 1: saumya
String 2: ansh
You can remove only 1 'a' and 1 's' from both the strings.
Remaining strings are:
String 1: umya
String 2: nh
Now all you need to do is find the sum of the remaining strings length % 6.
Output:
If obtained value is 1, output "Friends"
If obtained value is 2, output "Love"
If obtained value is 3, output "Affection"
If obtained value is 4, output "Marriage"
If obtained value is 5, output "Enemy"
If obtained value is 0, output "Siblings"You will be given two strings on different lines.
Constraints
1 <= Length of both the strings <= 100000Output a single string, the result of FLAMES test.Sample Input:-
saumya
ansh
Sample Output:-
Siblings
Explanation:-
after deleting characters :-
str1 = umya
str2 = nh
sum = 4+2
sum%6=0
, I have written this Solution Code: name1 = input().strip().lower()
name2 = input().strip().lower()
listA = [0]*26
listB = [0]*26
for i in name1:
listA[ord(i)-ord('a')] = listA[ord(i)-ord('a')] + 1
for i in name2:
listB[ord(i)-ord('a')] = listB[ord(i)-ord('a')] + 1
count = 0
for i in range(0,26):
count = count+abs(listA[i]-listB[i])
res = ["Siblings","Friends","Love","Affection", "Marriage", "Enemy"]
print(res[count%6]), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: They say friendship is greater than love. Why not play the famous game "FLAMES".
The rules are super simple. Given two strings (all lowercase), remove all the letters that are common to both the strings from both the strings. You cannot erase a character in first string whichever corresponding same character in other string not exist.
For example, in the case
String 1: saumya
String 2: ansh
You can remove only 1 'a' and 1 's' from both the strings.
Remaining strings are:
String 1: umya
String 2: nh
Now all you need to do is find the sum of the remaining strings length % 6.
Output:
If obtained value is 1, output "Friends"
If obtained value is 2, output "Love"
If obtained value is 3, output "Affection"
If obtained value is 4, output "Marriage"
If obtained value is 5, output "Enemy"
If obtained value is 0, output "Siblings"You will be given two strings on different lines.
Constraints
1 <= Length of both the strings <= 100000Output a single string, the result of FLAMES test.Sample Input:-
saumya
ansh
Sample Output:-
Siblings
Explanation:-
after deleting characters :-
str1 = umya
str2 = nh
sum = 4+2
sum%6=0
, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
#define max1 10000001
int main(){
string s1,s2;
cin>>s1>>s2;
string a[6];
a[1]= "Friends";
a[2]= "Love";
a[3]="Affection";
a[4]= "Marriage";
a[5]= "Enemy";
a[0]= "Siblings";
int b[26],c[26];
for(int i=0;i<26;i++){b[i]=0;c[i]=0;}
for(int i=0;i<s1.length();i++){
b[s1[i]-'a']++;
}
for(int i=0;i<s2.length();i++){
c[s2[i]-'a']++;
}
int sum=0;
for(int i=0;i<26;i++){
sum+=abs(b[i]-c[i]);
}
cout<<a[sum%6];
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: For Christmas decoration, Jerry has set up N christmas lights in a row. The brightness of the i<sup>th</sup> light from the left is B[i]. A light at position i is powerful if its brightness is greater than or equal to the sum of brightness of all the lights to its left. Now, Tom wants the number of powerful lights to be maximum so he wants to rearrange the lights so that maximum number of lights are powerful. Find the maximum number of powerful lights, and make Tom and Jerry happy this Christmas.The first line of the input contains a single integer N.
The next line contain N integers denoting array B.
Constraints
1 <= N <= 100000
1 <= B[i] <= 10<sup>15</sup>Print a single integer denoting maximum number of powerful lights after rearrangement.Sample Input 1
5
10 1 3 23 3
Sample Output 1
4
Explanation: we can rearrange the lights as 1 3 10 23 3. In this lights at index 1, 2, 3 and 4 are powerful.
Sample Input 2
5
1 1 1 1 1
Sample Output 2
2, I have written this Solution Code: import java.io.*;
import java.util.*;
public class Main {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve(int TC) throws Exception {
int n = ni();
long[] a = new long[n];
for(int i=0;i<n;i++) {
a[i] = nl();
}
long sum = 0, ans = 0;
Arrays.sort(a);
for(long i: a) {
if(i >= sum) {
++ ans;
sum += i;
}
}
pn(ans);
}
boolean TestCases = false;
public static void main(String[] args) throws Exception { new Main().run(); }
void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
static void dbg(Object... o){System.err.println(Arrays.deepToString(o));}
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
int T = TestCases ? ni() : 1;
for(int t=1;t<=T;t++) solve(t);
out.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}
void p(Object o) { out.print(o); }
void pn(Object o) { out.println(o); }
void pni(Object o) { out.println(o);out.flush(); }
int ni() {
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-') {
minus = true;
b = readByte();
}
while(true) {
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
long nl() {
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-') {
minus = true;
b = readByte();
}
while(true) {
if(b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
double nd() { return Double.parseDouble(ns()); }
char nc() { return (char)skip(); }
int BUF_SIZE = 1024 * 8;
byte[] inbuf = new byte[BUF_SIZE];
int lenbuf = 0, ptrbuf = 0;
int readByte() {
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
} return inbuf[ptrbuf++];
}
boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))) {
sb.appendCodePoint(b); b = readByte();
} return sb.toString();
}
char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
} return n == p ? buf : Arrays.copyOf(buf, p);
}
void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); }
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: For Christmas decoration, Jerry has set up N christmas lights in a row. The brightness of the i<sup>th</sup> light from the left is B[i]. A light at position i is powerful if its brightness is greater than or equal to the sum of brightness of all the lights to its left. Now, Tom wants the number of powerful lights to be maximum so he wants to rearrange the lights so that maximum number of lights are powerful. Find the maximum number of powerful lights, and make Tom and Jerry happy this Christmas.The first line of the input contains a single integer N.
The next line contain N integers denoting array B.
Constraints
1 <= N <= 100000
1 <= B[i] <= 10<sup>15</sup>Print a single integer denoting maximum number of powerful lights after rearrangement.Sample Input 1
5
10 1 3 23 3
Sample Output 1
4
Explanation: we can rearrange the lights as 1 3 10 23 3. In this lights at index 1, 2, 3 and 4 are powerful.
Sample Input 2
5
1 1 1 1 1
Sample Output 2
2, I have written this Solution Code: def lights(x):
sum = 0
count = 0
for i in x:
if i >= sum:
count += 1
sum += i
return count
if __name__ == '__main__':
n = int(input())
x = input().split()
for i in range(len(x)):
x[i] = int(x[i])
x.sort()
print(lights(x)), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: For Christmas decoration, Jerry has set up N christmas lights in a row. The brightness of the i<sup>th</sup> light from the left is B[i]. A light at position i is powerful if its brightness is greater than or equal to the sum of brightness of all the lights to its left. Now, Tom wants the number of powerful lights to be maximum so he wants to rearrange the lights so that maximum number of lights are powerful. Find the maximum number of powerful lights, and make Tom and Jerry happy this Christmas.The first line of the input contains a single integer N.
The next line contain N integers denoting array B.
Constraints
1 <= N <= 100000
1 <= B[i] <= 10<sup>15</sup>Print a single integer denoting maximum number of powerful lights after rearrangement.Sample Input 1
5
10 1 3 23 3
Sample Output 1
4
Explanation: we can rearrange the lights as 1 3 10 23 3. In this lights at index 1, 2, 3 and 4 are powerful.
Sample Input 2
5
1 1 1 1 1
Sample Output 2
2, 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 n;
cin>>n;
int a[n];
for(int i=0;i<n;++i){
cin>>a[i];
}
sort(a,a+n);
int ans=0;
int v=0;
for(int i=0;i<n;++i){
if(a[i]>=v){
++ans;
v+=a[i];
}
}
cout<<ans;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a positive number X. Find all Jumping Numbers smaller than or equal to X.
Jumping Number: A number is called Jumping Number if all adjacent digits in it differ by only 1. All single-digit numbers are considered as Jumping Numbers. For example 7, 8987 and 4343456 are Jumping numbers but 796 and 89098 are not.The first line of the input contains T denoting the number of test cases. Each test case contains a positive number N.
Constraints:
1 <= T <= 50
1 <= N <= 10^8For each test case, print a single line containing all the Jumping numbers less than or equal to N from 1 in increasing orderSample Input:
2
10
50
Sample Output:
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10 12 21 23 32 34 43 45
Explanation:
Testcase 2: Here, the most significant digits of each jumping number is following increasing order, i.e., jumping numbers starting from 0, followed by 1, then 2 and so on, themselves being in increasing order 2, 21, 23., 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++)
{
int n=Integer.parseInt(br.readLine());
Queue<Integer> q=new LinkedList<>();
int i=1;
while(i<=n)
{
if(i>9)
{
break;
}
System.out.print(i+" ");
q.add(i);
i++;
}
int newJumpingNo;
while(n>9)
{
i=q.remove();
int lastDigit=i%10;
if(lastDigit==0)
{
newJumpingNo=i*10+1;
if(newJumpingNo>n)
{
break;
}
System.out.print(newJumpingNo+" ");
q.add(newJumpingNo);
}
else if(lastDigit==9)
{
newJumpingNo=i*10+8;
if(newJumpingNo>n)
{
break;
}
System.out.print(newJumpingNo+" ");
q.add(newJumpingNo);
}
else{
newJumpingNo=i*10+(lastDigit-1);
if(newJumpingNo>n)
{
break;
}
System.out.print(newJumpingNo+" ");
q.add(newJumpingNo);
newJumpingNo=i*10+(lastDigit+1);
if(newJumpingNo>n)
{
break;
}
System.out.print(newJumpingNo+" ");
q.add(newJumpingNo);
}
}
System.out.println();
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a positive number X. Find all Jumping Numbers smaller than or equal to X.
Jumping Number: A number is called Jumping Number if all adjacent digits in it differ by only 1. All single-digit numbers are considered as Jumping Numbers. For example 7, 8987 and 4343456 are Jumping numbers but 796 and 89098 are not.The first line of the input contains T denoting the number of test cases. Each test case contains a positive number N.
Constraints:
1 <= T <= 50
1 <= N <= 10^8For each test case, print a single line containing all the Jumping numbers less than or equal to N from 1 in increasing orderSample Input:
2
10
50
Sample Output:
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10 12 21 23 32 34 43 45
Explanation:
Testcase 2: Here, the most significant digits of each jumping number is following increasing order, i.e., jumping numbers starting from 0, followed by 1, then 2 and so on, themselves being in increasing order 2, 21, 23., I have written this Solution Code: class Queue:
def __init__(self):
self.lst = []
def is_empty(self):
return self.lst == []
def enqueue(self, elem):
self.lst.append(elem)
def dequeue(self):
return self.lst.pop(0)
def bfs(x, num,l):
q = Queue()
q.enqueue(num)
while (not q.is_empty()):
num = q.dequeue()
if num<= x:
l.append(num)
last_dig = num % 10
if last_dig == 0:
q.enqueue((num * 10) + (last_dig + 1))
elif last_dig == 9:
q.enqueue((num * 10) + (last_dig - 1))
else:
q.enqueue((num * 10) + (last_dig - 1))
q.enqueue((num * 10) + (last_dig + 1))
def printJumping(x):
l=[]
for i in range(1, 10):
bfs(x, i,l)
l.sort()
for i in l:
print(i,end=" ")
print("")
t=int(input())
for i in range(t):
x = int(input())
printJumping(x), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a positive number X. Find all Jumping Numbers smaller than or equal to X.
Jumping Number: A number is called Jumping Number if all adjacent digits in it differ by only 1. All single-digit numbers are considered as Jumping Numbers. For example 7, 8987 and 4343456 are Jumping numbers but 796 and 89098 are not.The first line of the input contains T denoting the number of test cases. Each test case contains a positive number N.
Constraints:
1 <= T <= 50
1 <= N <= 10^8For each test case, print a single line containing all the Jumping numbers less than or equal to N from 1 in increasing orderSample Input:
2
10
50
Sample Output:
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10 12 21 23 32 34 43 45
Explanation:
Testcase 2: Here, the most significant digits of each jumping number is following increasing order, i.e., jumping numbers starting from 0, followed by 1, then 2 and so on, themselves being in increasing order 2, 21, 23., I have written this Solution Code: #include<bits/stdc++.h>
#define int long long
#define ll long long
#define pb push_back
#define endl '\n'
#define pii pair<int,int>
#define vi vector<int>
#define all(a) (a).begin(),(a).end()
#define F first
#define S second
#define sz(x) (int)x.size()
#define hell 1000000007
#define rep(i,a,b) for(int i=a;i<b;i++)
#define dep(i,a,b) for(int i=a;i>=b;i--)
#define lbnd lower_bound
#define ubnd upper_bound
#define bs binary_search
#define mp make_pair
using namespace std;
const int N = 1e2 + 5;
const int mod = 1e9 + 7;
const int inf = 1e9 + 9;
void solve(){
int t; cin >> t;
vector<int> v;
for(int i = 1; i <= 9; i++)
v.push_back(i);
for(int i = 0; i < (int)v.size(); i++){
int x = v[i]%10;
if(x-1 >= 0){
int nx = v[i]*10 + x-1;
if(nx <= inf)
v.push_back(nx);
}
if(x+1 <= 9){
int nx = v[i]*10 + x+1;
if(nx <= inf)
v.push_back(nx);
}
}
while(t--){
int n; cin >> n;
for(int i = 0; i < v.size(); i++){
if(v[i] <= n)
cout << v[i] << " ";
}
cout << endl;
}
}
void testcases(){
int tt = 1;
//cin >> tt;
while(tt--){
solve();
}
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
clock_t start = clock();
testcases();
cerr << (double)(clock() - start)*1000/CLOCKS_PER_SEC << " ms: ";
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: Given an unsorted array A of size N of non-negative integers, find a continuous sub-array which adds to a given number S.Each test case consists of two lines. The first line of each test case is N and S, where N is the size of the array and S is the sum. The second line of each test case contains N space-separated integers denoting the array elements.
<b>Constraints:-</b>
1 ≤ N ≤ 10<sup>5</sup>
1 ≤ Ai ≤ 10<sup>5</sup>Print the starting and ending positions (1 indexing) of first such occurring subarray from the left if sum equals to subarray, else print -1.Sample Input
5 12
1 2 3 7 5
Sample Output
2 4
Explanation:
subarray starting from index 2 and ending at index 4 => {2 , 3 , 7}
sum = 2 + 3 + 7 = 12
Sample Input
10 15
1 2 3 4 5 6 7 8 9 10
Sample Output
1 5, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws IOException
{
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String StrInput[] = br.readLine().trim().split(" ");
int n = Integer.parseInt(StrInput[0]);
int s = Integer.parseInt(StrInput[1]);
int arr[] = new int[n];
String StrInput2[] = br.readLine().trim().split(" ");
for(int i=0;i<n;i++)
{
arr[i] = Integer.parseInt(StrInput2[i]);
}
int sum = arr[0];
int startingindex = 0;
int endingindex = 1;
int j = 0;
int i;
for(i=1;i<=n;i++)
{
if(sum < s && arr[i] != 0)
{
sum += arr[i];
}
while(sum > s && startingindex < i-1)
{
sum -= arr[startingindex];
startingindex++;
}
if(sum == s)
{
endingindex = i+1;
if(arr[0] == 0)
{
System.out.print(startingindex+2 + " " + endingindex);
}
else
{
System.out.print(startingindex+1 + " "+ endingindex);
}
break;
}
if(i == n && sum < s)
{
System.out.print(-1);
break;
}
}
}
catch(Exception e)
{
System.out.print(-1);
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an unsorted array A of size N of non-negative integers, find a continuous sub-array which adds to a given number S.Each test case consists of two lines. The first line of each test case is N and S, where N is the size of the array and S is the sum. The second line of each test case contains N space-separated integers denoting the array elements.
<b>Constraints:-</b>
1 ≤ N ≤ 10<sup>5</sup>
1 ≤ Ai ≤ 10<sup>5</sup>Print the starting and ending positions (1 indexing) of first such occurring subarray from the left if sum equals to subarray, else print -1.Sample Input
5 12
1 2 3 7 5
Sample Output
2 4
Explanation:
subarray starting from index 2 and ending at index 4 => {2 , 3 , 7}
sum = 2 + 3 + 7 = 12
Sample Input
10 15
1 2 3 4 5 6 7 8 9 10
Sample Output
1 5, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
int main(){
int n,k;
cin>>n>>k;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
int sum=0;
unordered_map<int,int> m;
for(int i=0;i<n;i++){
sum+=a[i];
if(sum==k){cout<<1<<" "<<i+1;return 0;}
if(m.find(sum-k)!=m.end()){
cout<<m[sum-k]+2<<" "<<i+1;
return 0;
}
m[sum]=i;
}
cout<<-1;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an unsorted array A of size N of non-negative integers, find a continuous sub-array which adds to a given number S.Each test case consists of two lines. The first line of each test case is N and S, where N is the size of the array and S is the sum. The second line of each test case contains N space-separated integers denoting the array elements.
<b>Constraints:-</b>
1 ≤ N ≤ 10<sup>5</sup>
1 ≤ Ai ≤ 10<sup>5</sup>Print the starting and ending positions (1 indexing) of first such occurring subarray from the left if sum equals to subarray, else print -1.Sample Input
5 12
1 2 3 7 5
Sample Output
2 4
Explanation:
subarray starting from index 2 and ending at index 4 => {2 , 3 , 7}
sum = 2 + 3 + 7 = 12
Sample Input
10 15
1 2 3 4 5 6 7 8 9 10
Sample Output
1 5, I have written this Solution Code: def sumFinder(N,S,a):
currentSum = a[0]
start = 0
i = 1
while i <= N:
while currentSum > S and start < i-1:
currentSum = currentSum - a[start]
start += 1
if currentSum == S:
return (start+1,i)
if i < N:
currentSum = currentSum + a[i]
i += 1
return(-1)
N, S = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
ans = sumFinder(N,S,a)
if(ans==-1):
print(ans)
else:
print(ans[0],ans[1]), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Everyone has heard of palindromes, right! A palindrome is a string that remains the same if reversed.
Let's define a new term, Dalindrome.
A Dalindrome is a string whose atleast one of the substrings is a palindrome.
Given a string, find whether it's a Dalindrome.The only line of input contains a string to be checked.
Constraints
1 <= length of string <= 100Output "Yes" if string is a Dalindrome, else output "No".Sample Input
cbabcc
Sample Output
Yes
Explanation: "bab" is one of the substrings of the string that is a palindrome. There may be other substrings that are palindrome as well like "cc", or "cbabc". The question requires atleast one., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) {
System.out.println("Yes");
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Everyone has heard of palindromes, right! A palindrome is a string that remains the same if reversed.
Let's define a new term, Dalindrome.
A Dalindrome is a string whose atleast one of the substrings is a palindrome.
Given a string, find whether it's a Dalindrome.The only line of input contains a string to be checked.
Constraints
1 <= length of string <= 100Output "Yes" if string is a Dalindrome, else output "No".Sample Input
cbabcc
Sample Output
Yes
Explanation: "bab" is one of the substrings of the string that is a palindrome. There may be other substrings that are palindrome as well like "cc", or "cbabc". The question requires atleast one., I have written this Solution Code: string = str(input())
print("Yes"), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Everyone has heard of palindromes, right! A palindrome is a string that remains the same if reversed.
Let's define a new term, Dalindrome.
A Dalindrome is a string whose atleast one of the substrings is a palindrome.
Given a string, find whether it's a Dalindrome.The only line of input contains a string to be checked.
Constraints
1 <= length of string <= 100Output "Yes" if string is a Dalindrome, else output "No".Sample Input
cbabcc
Sample Output
Yes
Explanation: "bab" is one of the substrings of the string that is a palindrome. There may be other substrings that are palindrome as well like "cc", or "cbabc". The question requires atleast one., 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 = 100005;
// 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
signed main()
{
fast
#ifdef SWAPNIL07
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
string s; cin>>s;
cout<<"Yes";
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given N activities with their start and finish times as S and F. Find the maximum number of activities that can be performed by a single person, assuming that a person can only work on a single activity at a time.The first line of input contains one integer denoting N.
Next N lines contain two space-separated integers denoting the start time and finish time for the ith activity.
Constraints
1 ≤ N ≤ 10^6
1 ≤ S[i] <= F[i] ≤ 10^9Output one integer, the maximum number of activities that can be performedSample Input
6
1 2
3 4
1 6
5 7
8 9
5 9
Sample Output
4
Explanation:-
He can perform activity 1 2 4 5
Sample Input:-
4
4 6
5 6
3 5
6 8
Sample Output:-
2, I have written this Solution Code: #include<bits/stdc++.h>
//#define int long long
#define ll long long
#define pb push_back
#define endl '\n'
#define pi pair<int,int>
#define vi vector<int>
#define all(a) (a).begin(),(a).end()
#define fi first
#define se second
#define sz(x) (int)x.size()
#define hell 1000000007
#define rep(i,a,b) for(int i=a;i<b;i++)
#define dep(i,a,b) for(int i=a;i>=b;i--)
#define lbnd lower_bound
#define ubnd upper_bound
#define bs binary_search
#define mp make_pair
using namespace std;
const int N = 2e5 + 5;
const int mod = 1e9 + 7;
const int inf = 1e9 + 9;
pi a[N];
int dp[N];
map<int, int> m;
vector<int> v[N];
void solve(){
int n; cin >> n;
for(int i = 1; i <= n; i++){
cin >> a[i].fi >> a[i].se;
m[a[i].fi] = m[a[i].se] = 1;
}
int p = 1;
for(auto &i: m){
i.se += p;
p = i.se;
}
for(int i = 1; i <= n; i++){
a[i].fi = m[a[i].fi];
a[i].se = m[a[i].se];
v[a[i].se].push_back(a[i].fi);
}
for(int i = 1; i < N; i++){
dp[i] = dp[i-1];
for(auto j: v[i])
dp[i] = max(dp[i], 1 + dp[j-1]);
}
cout << dp[N-2];
}
void testcases(){
int tt = 1;
//cin >> tt;
while(tt--){
solve();
}
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
clock_t start = clock();
testcases();
cerr << (double)(clock() - start)*1000/CLOCKS_PER_SEC << " ms: ";
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Find number of ways an integer N can be represented as a sum of unique natural numbers.First line contain an integer T denoting number of test cases. Each test case contains a single integer N.
Constraint:-
1 <= T <= 100
0 <= N <= 120Print a single integer containing number of ways.Sample input
4
6
1
4
2
Sample output:-
4
1
2
1
Explanation:-
TestCase1:-
6 can be represented as (1, 2, 3), (1, 5), (2, 4), (6), 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 t = Integer.parseInt(br.readLine());
for(int i=0;i<t;i++){
int n = Integer.parseInt(br.readLine());
System.out.println(Ways(n,1));
}
}
static int Ways(int x, int num)
{
int val =(x - num);
if (val == 0)
return 1;
if (val < 0)
return 0;
return Ways(val, num + 1) + Ways(x, num + 1);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Find number of ways an integer N can be represented as a sum of unique natural numbers.First line contain an integer T denoting number of test cases. Each test case contains a single integer N.
Constraint:-
1 <= T <= 100
0 <= N <= 120Print a single integer containing number of ways.Sample input
4
6
1
4
2
Sample output:-
4
1
2
1
Explanation:-
TestCase1:-
6 can be represented as (1, 2, 3), (1, 5), (2, 4), (6), I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
long cnt=0;
int j;
void sum(int X,int j) {
if(X==0){cnt++;}
if(X<0)
{return;}
else {
for(int i=j;i<=(X);i++){
X=X-i;
sum(X,i+1);
X=X+i;
}
}
}
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
if(n<1){cout<<0<<endl;continue;}
sum(n,1);
cout<<cnt<<endl;
cnt=0;
}
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Find number of ways an integer N can be represented as a sum of unique natural numbers.First line contain an integer T denoting number of test cases. Each test case contains a single integer N.
Constraint:-
1 <= T <= 100
0 <= N <= 120Print a single integer containing number of ways.Sample input
4
6
1
4
2
Sample output:-
4
1
2
1
Explanation:-
TestCase1:-
6 can be represented as (1, 2, 3), (1, 5), (2, 4), (6), I have written this Solution Code: // ignore number of testcases
// n is the number as provided in input
function numberOfWays(n) {
// write code here
// do not console.log the answer
// return answer as a number
if(n < 1) return 0;
let cnt = 0;
let j;
function sum(X, j) {
if (X == 0) { cnt++; }
if (X < 0) { return; }
else {
for (let i = j; i <= X; i++) {
X = X - i;
sum(X, i + 1);
X = X + i;
}
}
}
sum(n,1);
return cnt
}
, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Find number of ways an integer N can be represented as a sum of unique natural numbers.First line contain an integer T denoting number of test cases. Each test case contains a single integer N.
Constraint:-
1 <= T <= 100
0 <= N <= 120Print a single integer containing number of ways.Sample input
4
6
1
4
2
Sample output:-
4
1
2
1
Explanation:-
TestCase1:-
6 can be represented as (1, 2, 3), (1, 5), (2, 4), (6), I have written this Solution Code: for _ in range(int(input())):
x = int(input())
n = 1
dp = [1] + [0] * x
for i in range(1, x + 1):
u = i ** n
for j in range(x, u - 1, -1):
dp[j] += dp[j - u]
if x==0:
print(0)
else:
print(dp[-1]), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array arr[] and a number K where K is not greater than the size of array, the task is to find the Kth smallest element in the given array. It is given that all array elements are distinct.
<b>Note:</b>
Do Not Use sort() STL function, Use heap data structure.The input line contains T, denoting the number of test cases. Each test case consists of two lines. The first line of each test case contains two integers N and K. Second-line contains N space-separated integer denoting elements of the array.
<b>Constraints:</b>
1 <= T <= 50
1 <= N <= 10000
1 <= K <= N
1 <= arr[i] <= 10<sup>6</sup>Corresponding to each test case, print the kth smallest element in a new line.Sample Input
1
6 3
7 10 4 3 20 15
Sample Output
7
<b>Explanation:</b>
Sorted array: 3 4 7 10 15 20, 7 is the third element, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void sort(int arr[])
{
int n = arr.length;
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
for (int i = n - 1; i > 0; i--) {
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
heapify(arr, i, 0);
}
}
static void heapify(int arr[], int n, int i)
{
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < n && arr[l] > arr[largest])
largest = l;
if (r < n && arr[r] > arr[largest])
largest = r;
if (largest != i) {
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
heapify(arr, n, largest);
}
}
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0) {
int n = sc.nextInt();
int k = sc.nextInt();
int[] arr = new int[n];
for(int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
sort(arr);
System.out.println(arr[k-1]);
arr=null;
System.gc();
}
sc.close();
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array arr[] and a number K where K is not greater than the size of array, the task is to find the Kth smallest element in the given array. It is given that all array elements are distinct.
<b>Note:</b>
Do Not Use sort() STL function, Use heap data structure.The input line contains T, denoting the number of test cases. Each test case consists of two lines. The first line of each test case contains two integers N and K. Second-line contains N space-separated integer denoting elements of the array.
<b>Constraints:</b>
1 <= T <= 50
1 <= N <= 10000
1 <= K <= N
1 <= arr[i] <= 10<sup>6</sup>Corresponding to each test case, print the kth smallest element in a new line.Sample Input
1
6 3
7 10 4 3 20 15
Sample Output
7
<b>Explanation:</b>
Sorted array: 3 4 7 10 15 20, 7 is the third element, I have written this Solution Code: for _ in range(int(input())):
s,k = map(int,input().split())
lis=list(map(int,input().split()))
lis.sort()
print(lis[k-1]), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array arr[] and a number K where K is not greater than the size of array, the task is to find the Kth smallest element in the given array. It is given that all array elements are distinct.
<b>Note:</b>
Do Not Use sort() STL function, Use heap data structure.The input line contains T, denoting the number of test cases. Each test case consists of two lines. The first line of each test case contains two integers N and K. Second-line contains N space-separated integer denoting elements of the array.
<b>Constraints:</b>
1 <= T <= 50
1 <= N <= 10000
1 <= K <= N
1 <= arr[i] <= 10<sup>6</sup>Corresponding to each test case, print the kth smallest element in a new line.Sample Input
1
6 3
7 10 4 3 20 15
Sample Output
7
<b>Explanation:</b>
Sorted array: 3 4 7 10 15 20, 7 is the third element, 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, k;
cin >> n >> k;
priority_queue<int> s;
for(int i = 1; i <= n; i++){
int p; cin >> p;
s.push(-p);
}
int ans = 0;
while(k--){
ans = -s.top();
s.pop();
}
cout << ans << endl;
}
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: N people are standing in a queue in which A of them like apple and B of them like oranges. How many people like both apple and oranges.
<b>Note</b>:- It is guaranteed that each and every person likes at least one of the given two.<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>LikesBoth()</b> that takes integers N, A, and B as arguments.
Constraints:-
1 <= N <= 10000
1 <= A <= N
1 <= B <= NReturn the number of people that like both of the fruit.Sample Input:-
5 3 4
Sample Output:-
2
Sample Input:-
5 5 5
Sample Output:-
5, I have written this Solution Code: static int LikesBoth(int N, int A, int B){
return (A+B-N);
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: N people are standing in a queue in which A of them like apple and B of them like oranges. How many people like both apple and oranges.
<b>Note</b>:- It is guaranteed that each and every person likes at least one of the given two.<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>LikesBoth()</b> that takes integers N, A, and B as arguments.
Constraints:-
1 <= N <= 10000
1 <= A <= N
1 <= B <= NReturn the number of people that like both of the fruit.Sample Input:-
5 3 4
Sample Output:-
2
Sample Input:-
5 5 5
Sample Output:-
5, I have written this Solution Code: def LikesBoth(N,A,B):
return (A+B-N)
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: N people are standing in a queue in which A of them like apple and B of them like oranges. How many people like both apple and oranges.
<b>Note</b>:- It is guaranteed that each and every person likes at least one of the given two.<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>LikesBoth()</b> that takes integers N, A, and B as arguments.
Constraints:-
1 <= N <= 10000
1 <= A <= N
1 <= B <= NReturn the number of people that like both of the fruit.Sample Input:-
5 3 4
Sample Output:-
2
Sample Input:-
5 5 5
Sample Output:-
5, I have written this Solution Code: int LikesBoth(int N,int A, int B){
return (A+B-N);
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: N people are standing in a queue in which A of them like apple and B of them like oranges. How many people like both apple and oranges.
<b>Note</b>:- It is guaranteed that each and every person likes at least one of the given two.<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>LikesBoth()</b> that takes integers N, A, and B as arguments.
Constraints:-
1 <= N <= 10000
1 <= A <= N
1 <= B <= NReturn the number of people that like both of the fruit.Sample Input:-
5 3 4
Sample Output:-
2
Sample Input:-
5 5 5
Sample Output:-
5, I have written this Solution Code: int LikesBoth(int N,int A, int B){
return (A+B-N);
}, In this Programming Language: C, Now tell me if this Code is compilable or not? | Compilable |
For this Question: There is a room filled with letters. Newton can choose exactly three letters C<sub>1</sub>, C<sub>2</sub> and C<sub>3</sub>. If all of them are the same letter, then it is considered as a win.
Determine whether Newton wins.The first line contains three letters C<sub>1</sub>, C<sub>2</sub> and C<sub>3</sub>.
<b>Constraints</b>
C<sub>i</sub> is an uppercase English letter.If the result is a win, print Won; otherwise, print Lost.<b>Sample Input 1:</b>
SSS
<b>Sample Output 1:</b>
Won
<b>Sample Explanation 1:</b>
All of them are the same letter, so it is a win.
<b>Sample Input 2:</b>
WVW
<b>Sample Output 2:</b>
Lost
<b>Sample Explanation 2:</b>
It is not a win., I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
const int sz=100000+4;
int arr1[3];
int arr2[3];
int main()
{
string s;
cin >>s;
for (int i =0;i<s.length();i++){
if (s[i]==s[i+1]&&s[i+1]==s[i+2]){
cout <<"Won"<<'\n';
break;
}
else cout <<"Lost"<<'\n';
break;
}
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: A number is called Silly if it can be represented as the sum of the square of consecutive natural numbers starting from 1.
For a given number N, find the closest silly number.<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>SillyNumber()</b> that takes integer N as argument.
Constraints:-
1 <= N <= 100000Return the closest Silly number.
Note:- If more than one answer exists return the minimum one.Sample Input:-
18
Sample Output:-
14
Explanation:-
1*1 + 2*2 + 3*3 = 14
Sample Input:-
2
Sample Output:-
1, I have written this Solution Code: static int SillyNumber(int N){
int sum=0;
int x=1;
while(sum<N){
sum+=x*x;
x++;
}
x--;
if(sum-N < N-(sum-x*x)){
return sum;
}
else{
return sum-x*x;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: A number is called Silly if it can be represented as the sum of the square of consecutive natural numbers starting from 1.
For a given number N, find the closest silly number.<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>SillyNumber()</b> that takes integer N as argument.
Constraints:-
1 <= N <= 100000Return the closest Silly number.
Note:- If more than one answer exists return the minimum one.Sample Input:-
18
Sample Output:-
14
Explanation:-
1*1 + 2*2 + 3*3 = 14
Sample Input:-
2
Sample Output:-
1, I have written this Solution Code: int SillyNumber(int N){
int sum=0;
int x=1;
while(sum<N){
sum+=x*x;
x++;
}
x--;
if(sum-N < N-(sum-x*x)){
return sum;
}
else{
return sum-x*x;
}
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: A number is called Silly if it can be represented as the sum of the square of consecutive natural numbers starting from 1.
For a given number N, find the closest silly number.<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>SillyNumber()</b> that takes integer N as argument.
Constraints:-
1 <= N <= 100000Return the closest Silly number.
Note:- If more than one answer exists return the minimum one.Sample Input:-
18
Sample Output:-
14
Explanation:-
1*1 + 2*2 + 3*3 = 14
Sample Input:-
2
Sample Output:-
1, I have written this Solution Code: int SillyNumber(int N){
int sum=0;
int x=1;
while(sum<N){
sum+=x*x;
x++;
}
x--;
if(sum-N < N-(sum-x*x)){
return sum;
}
else{
return sum-x*x;
}
}, In this Programming Language: C, Now tell me if this Code is compilable or not? | Compilable |
For this Question: A number is called Silly if it can be represented as the sum of the square of consecutive natural numbers starting from 1.
For a given number N, find the closest silly number.<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>SillyNumber()</b> that takes integer N as argument.
Constraints:-
1 <= N <= 100000Return the closest Silly number.
Note:- If more than one answer exists return the minimum one.Sample Input:-
18
Sample Output:-
14
Explanation:-
1*1 + 2*2 + 3*3 = 14
Sample Input:-
2
Sample Output:-
1, I have written this Solution Code: def SillyNumber(N):
sum=0
x=1
while sum<N:
sum=sum+x*x
x=x+1
x=x-1
if (sum-N) < (N-(sum-x*x)):
return sum;
else:
return sum - x*x
, 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: 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: 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: Newton is given an array S of N integers S<sub>1</sub>, S<sub>2</sub>,. . S<sub>N</sub>. He needs to perform some function on every subarray of the given array S whose starting element is the first element of the given array S.
The function is as follows:
Given an array A of size N, for each i from 1 to N, add the current maximum of the array A to A<sub>i</sub>. Then calculate the sum of the resultant array.
Perform this function on all the subarrays whose starting element is the starting element of the given array S.The first line of the input contains a single integer N
The next line contains N different integers S<sub>1</sub>, S<sub>2</sub>,. . S<sub>N</sub>
<b>Constraints:</b>
1 <= N <= 4 x 10<sup>5</sup>
1 <= S<sub>i</sub> <= 2 x 10<sup>7</sup>Print the answer for each subarray in a single line<b>Sample Input 1:</b>
3
2 4 6
<b>Sample Output 1:</b>
4
16
38
<b>Explanation:</b>
Lets apply the function to the subarray [2, 4]:
1) For index 1, the current maximum of the array is 4, So the array changes to [6, 4]
2) For index 2, the current maximum of the array is 6, So the array changes to [6, 10]
Now the sum of the resultant array is 6+10 = 16
Similarly the output for the subarray [2] is 4 and for the subarray [2, 4, 6] is 38
<b>Sample Input 2:</b>
5
1 2 3 4 5
<b>Sample Output 2:</b>
2
8
19
36
60, 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 n; cin>>n;
vll a(n), t(n);
F0(i, n) cin>>a[i], t[i] = a[i];
F1(i, n-1) t[i] += t[i-1];
ll mx = -1, sum = 0;
F0(i, n) mx = max(mx, a[i]), sum += t[i], cout<<sum+(i+1)*mx<<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: Given a boolean matrix of size N*M in which each row is sorted your task is to print the index of the row containing maximum 1's. If multiple answer exist print the smallest one.First line contains two space separated integers denoting values of N and M. Next N lines contains M space separated integers depicting the values of the matrix.
Constraints:-
1 < = M, N < = 1000
0 < = Matrix[][] < = 1Print the smallest index (0 indexing) of a row containing the maximum number of 1's.Sample Input:-
3 5
0 1 1 1 1
0 0 0 1 1
0 0 0 1 1
Sample Output:-
0
Sample Input:-
4 4
0 1 1 1
1 1 1 1
0 0 1 1
1 1 1 1
Sample Output:-
1, I have written this Solution Code: import java.io.*;
import java.util.*;
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')break;
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 void main (String[] args) throws IOException{
Reader sc = new Reader();
int m = sc.nextInt();
int n = sc.nextInt();
int[][] arr = new int[m][n];
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
arr[i][j] = sc.nextInt();
}
}
int max_row_index = 0;
int j = n - 1;
for (int i = 0; i < m; i++) {
while (j >= 0 && arr[i][j] == 1) {
j = j - 1;
max_row_index = i;
}
}
System.out.println(max_row_index);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a boolean matrix of size N*M in which each row is sorted your task is to print the index of the row containing maximum 1's. If multiple answer exist print the smallest one.First line contains two space separated integers denoting values of N and M. Next N lines contains M space separated integers depicting the values of the matrix.
Constraints:-
1 < = M, N < = 1000
0 < = Matrix[][] < = 1Print the smallest index (0 indexing) of a row containing the maximum number of 1's.Sample Input:-
3 5
0 1 1 1 1
0 0 0 1 1
0 0 0 1 1
Sample Output:-
0
Sample Input:-
4 4
0 1 1 1
1 1 1 1
0 0 1 1
1 1 1 1
Sample Output:-
1, I have written this Solution Code: r, c = list(map(int, input().split()))
max_count = 0
max_r = 0
for i in range(r):
count = input().count("1")
if count > max_count:
max_count = count
max_r = i
print(max_r), 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 in which each row is sorted your task is to print the index of the row containing maximum 1's. If multiple answer exist print the smallest one.First line contains two space separated integers denoting values of N and M. Next N lines contains M space separated integers depicting the values of the matrix.
Constraints:-
1 < = M, N < = 1000
0 < = Matrix[][] < = 1Print the smallest index (0 indexing) of a row containing the maximum number of 1's.Sample Input:-
3 5
0 1 1 1 1
0 0 0 1 1
0 0 0 1 1
Sample Output:-
0
Sample Input:-
4 4
0 1 1 1
1 1 1 1
0 0 1 1
1 1 1 1
Sample Output:-
1, 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 1001
#define MOD 1000000007
#define read(type) readInt<type>()
#define out(x) cout<<x<<'\n'
#define out1(x) cout<<x<<" "
#define END cout<<'\n'
void fast(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}
int a[max1][max1];
signed main()
{
int n,m;
cin>>n>>m;
FOR(i,n){
FOR(j,m){cin>>a[i][j];}}
int cnt=0;
int ans=0;
int res=0;
FOR(i,n){
cnt=0;
FOR(j,m){
if(a[i][j]==1){
cnt++;
}}
if(cnt>res){
res=cnt;
ans=i;
}
}
out(ans);
}
, 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 in which each row is sorted your task is to print the index of the row containing maximum 1's. If multiple answer exist print the smallest one.First line contains two space separated integers denoting values of N and M. Next N lines contains M space separated integers depicting the values of the matrix.
Constraints:-
1 < = M, N < = 1000
0 < = Matrix[][] < = 1Print the smallest index (0 indexing) of a row containing the maximum number of 1's.Sample Input:-
3 5
0 1 1 1 1
0 0 0 1 1
0 0 0 1 1
Sample Output:-
0
Sample Input:-
4 4
0 1 1 1
1 1 1 1
0 0 1 1
1 1 1 1
Sample Output:-
1, I have written this Solution Code: // mat is the matrix/ 2d array
// n,m are dimensions
function max1Row(mat, n, m) {
// write code here
// do not console.log
// return the answer as a number
let j, max_row_index = 0;
j = m - 1;
for (let i = 0; i < n; i++)
{
// Move left until a 0 is found
let flag = false;
// to check whether a row has more 1's than previous
while (j >= 0 && mat[i][j] == 1)
{
j = j - 1; // Update the index of leftmost 1
// seen so far
flag = true;//present row has more 1's than previous
}
// if the present row has more 1's than previous
if (flag)
{
max_row_index = i; // Update max_row_index
}
}
if (max_row_index == 0 && mat[0][m - 1] == 0)
return -1;
return max_row_index;
}
, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: <b> The only difference between the easy and the tricky version is the constraint on the number of queries Q. Solving the tricky version automatically solves the easy version.</b>
You are given an array A of N integers. You will be given Q queries with two integers L and R. For each query, you need to find the sum of all elements of the array excluding the elements in the range [L, R] (both inclusive) modulo 10<sup>9</sup>+7.The first line of the input contains an integer N, the size of the array.
The second line of the input contains N integers, the elements of the array A.
The third line of the input contains an integer Q.
The next Q lines contain two integers L and R.
Constraints
1 <= N <= 200000
1 <= A[i] <= 1000000000
1 <= Q <= 100000
1 <= L <= R <= NOutput Q lines, each having a single integer the answer to Q-th query modulo 10<sup>9</sup>+7.Sample Input
4
5 3 3 1
2
2 3
4 4
Sample Output
6
11
Explanation: The array A = [5, 3, 3, 1].
First Query: Sum = 5 + 1 = 6.
Second Query: Sum = 5 + 3 + 3 = 11, I have written this Solution Code: import java.io.*;
import java.util.*;
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 void main (String[] args) throws IOException {
Reader sc = new Reader();
int arrSize = sc.nextInt();
long[] arr = new long[arrSize];
for(int i = 0; i < arrSize; i++)
{
arr[i] = sc.nextLong();
}
long[] prefix = new long[arrSize];
prefix[0] = arr[0];
for(int i = 1; i < arrSize; i++)
{
long val = 1000000007;
prefix[i - 1] %= val;
long prefixSum = prefix[i - 1] + arr[i];
prefixSum %= val;
prefix[i] = prefixSum;
}
long[] suffix = new long[arrSize];
suffix[arrSize - 1] = arr[arrSize - 1];
for(int i = arrSize - 2; i >= 0; i--)
{
long val = 1000000007;
suffix[i + 1] %= val;
long suffixSum = suffix[i + 1] + arr[i];
suffixSum %= val;
suffix[i] = suffixSum;
}
int query = sc.nextInt();
for(int x = 1; x <= query; x++)
{
int l = sc.nextInt();
int r = sc.nextInt();
long val = 1000000007;
long ans = 0;
ans += (l != 1 ? prefix[l-2] : 0);
ans %= val;
ans += (r != arrSize ? suffix[r] : 0);
ans %= val;
System.out.println(ans);
}
}
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: <b> The only difference between the easy and the tricky version is the constraint on the number of queries Q. Solving the tricky version automatically solves the easy version.</b>
You are given an array A of N integers. You will be given Q queries with two integers L and R. For each query, you need to find the sum of all elements of the array excluding the elements in the range [L, R] (both inclusive) modulo 10<sup>9</sup>+7.The first line of the input contains an integer N, the size of the array.
The second line of the input contains N integers, the elements of the array A.
The third line of the input contains an integer Q.
The next Q lines contain two integers L and R.
Constraints
1 <= N <= 200000
1 <= A[i] <= 1000000000
1 <= Q <= 100000
1 <= L <= R <= NOutput Q lines, each having a single integer the answer to Q-th query modulo 10<sup>9</sup>+7.Sample Input
4
5 3 3 1
2
2 3
4 4
Sample Output
6
11
Explanation: The array A = [5, 3, 3, 1].
First Query: Sum = 5 + 1 = 6.
Second Query: Sum = 5 + 3 + 3 = 11, I have written this Solution Code: n = int(input())
arr = list(map(int ,input().rstrip().split(" ")))
temp = 0
modified = []
for i in range(n):
temp = temp + arr[i]
modified.append(temp)
q = int(input())
for i in range(q):
s = list(map(int ,input().rstrip().split(" ")))
l = s[0]
r = s[1]
sum = 0
sum = ((modified[l-1]-arr[l-1])+(modified[n-1]-modified[r-1]))%1000000007
print(sum), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: <b> The only difference between the easy and the tricky version is the constraint on the number of queries Q. Solving the tricky version automatically solves the easy version.</b>
You are given an array A of N integers. You will be given Q queries with two integers L and R. For each query, you need to find the sum of all elements of the array excluding the elements in the range [L, R] (both inclusive) modulo 10<sup>9</sup>+7.The first line of the input contains an integer N, the size of the array.
The second line of the input contains N integers, the elements of the array A.
The third line of the input contains an integer Q.
The next Q lines contain two integers L and R.
Constraints
1 <= N <= 200000
1 <= A[i] <= 1000000000
1 <= Q <= 100000
1 <= L <= R <= NOutput Q lines, each having a single integer the answer to Q-th query modulo 10<sup>9</sup>+7.Sample Input
4
5 3 3 1
2
2 3
4 4
Sample Output
6
11
Explanation: The array A = [5, 3, 3, 1].
First Query: Sum = 5 + 1 = 6.
Second Query: Sum = 5 + 3 + 3 = 11, 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; cin>>n;
vector<int> a(n+1);
vector<int> pre(n+1, 0);
int tot = 0;
For(i, 1, n+1){
cin>>a[i];
assert(a[i]>0LL && a[i]<=1000000000LL);
tot += a[i];
pre[i]=pre[i-1]+a[i];
}
int q; cin>>q;
while(q--){
int l, r; cin>>l>>r;
int s = tot - (pre[r]-pre[l-1]);
s %= MOD;
cout<<s<<"\n";
}
}
signed main()
{
fast
#ifdef SWAPNIL07
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int t=1;
// cin>>t;
while(t--){
solve();
}
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer Q representing the number of queries and an integer K. There are two types of queries:
(i) 1 x : Add the number x to the stream
(ii) 2 : Print the sum of last K numbers of the stream. If there are less than K numbers in the stream, print the sum of current stream.
Process all the queries.First line contains two integers Q and K.
Next Q lines contains the queries.
Constraints
1 <= Q <= 10^5
1 <= x <= 10^5
1 <= K <= Q
There is atleast one query of 2nd type. For each query of type 2, print the sum of last K numbers of the stream on a new line.Sample Input 1:
5 2
1 4
2
1 1
1 3
2
Output
4
4
Explanation:
Initial Stream = {}
Add 4. Stream = {4}
Sum of last two elements = 4
Add 1. Stream = {4, 1}
Add 3. Stream = {4, 1, 3}
Sum of last two elements = 4
Sample Input 2:
3 1
1 1
2
2
Output
1
1
Explanation
Initial Stream = {}
Add 1. Stream = {1}
Sum of last element = 1
Sum of last element = 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));
int n,k;
String line = br.readLine();
String[] strs = line.trim().split("\\s+");
n=Integer.parseInt(strs[0]);
k=Integer.parseInt(strs[1]);
Long sum=0L;
Queue<Integer>x=new LinkedList<Integer>();
while(n>0){
n--;
line = br.readLine();
strs = line.trim().split("\\s+");
int y=Integer.parseInt(strs[0]);
if(y==1){
y=Integer.parseInt(strs[1]);
x.add(y);
sum += y;
if (x.size() > k) {
sum -= x.peek();
x.remove();
}
}
else{
System.out.print(sum+"\n");
}
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer Q representing the number of queries and an integer K. There are two types of queries:
(i) 1 x : Add the number x to the stream
(ii) 2 : Print the sum of last K numbers of the stream. If there are less than K numbers in the stream, print the sum of current stream.
Process all the queries.First line contains two integers Q and K.
Next Q lines contains the queries.
Constraints
1 <= Q <= 10^5
1 <= x <= 10^5
1 <= K <= Q
There is atleast one query of 2nd type. For each query of type 2, print the sum of last K numbers of the stream on a new line.Sample Input 1:
5 2
1 4
2
1 1
1 3
2
Output
4
4
Explanation:
Initial Stream = {}
Add 4. Stream = {4}
Sum of last two elements = 4
Add 1. Stream = {4, 1}
Add 3. Stream = {4, 1, 3}
Sum of last two elements = 4
Sample Input 2:
3 1
1 1
2
2
Output
1
1
Explanation
Initial Stream = {}
Add 1. Stream = {1}
Sum of last element = 1
Sum of last element = 1, I have written this Solution Code: /**
* author: tourist1256
* created: 2022-06-14 14:26:47
**/
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
template <class T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <class key, class value, class cmp = std::less<key>>
using ordered_map = tree<key, value, cmp, rb_tree_tag, tree_order_statistics_node_update>;
// find_by_order(k) returns iterator to kth element starting from 0;
// order_of_key(k) returns count of elements strictly smaller than k;
#ifdef LOCAL
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
#define debug(...) 2351
#endif
#define int long long
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
inline int64_t random_long(long long l = LLONG_MIN, long long r = LLONG_MAX) {
uniform_int_distribution<int64_t> generator(l, r);
return generator(rng);
}
int32_t main() {
int Q, K;
cin >> Q >> K;
deque<int> st;
int sum = 0;
while (Q--) {
int x;
cin >> x;
if (x == 1) {
int y;
cin >> y;
if (st.size() == K) {
sum -= st.back();
st.pop_back();
st.push_front(y);
sum += y;
} else {
st.push_front(y);
sum += y;
}
} else {
cout << sum << "\n";
}
}
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a string s, find the first non-repeating character in the string and return its index. If it does not exist, return -1.First line of the input contains the string s.
<b>Constraints</b>
1<= s. length <= 100000Print the index of the first non- repeating character in a stringInput
s = "newtonschool"
Output
1
Explanation
"e" is the first non- repeating character in a string, 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 s = br.readLine();
System.out.print(nonRepeatChar(s));
}
static int nonRepeatChar(String s){
char count[] = new char[256];
for(int i=0; i< s.length(); i++){
count[s.charAt(i)]++;
}
for (int i=0; i<s.length(); i++) {
if (count[s.charAt(i)]==1){
return i;
}
}
return -1;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a string s, find the first non-repeating character in the string and return its index. If it does not exist, return -1.First line of the input contains the string s.
<b>Constraints</b>
1<= s. length <= 100000Print the index of the first non- repeating character in a stringInput
s = "newtonschool"
Output
1
Explanation
"e" is the first non- repeating character in a string, I have written this Solution Code: from collections import defaultdict
s=input()
d=defaultdict(int)
for i in s:
d[i]+=1
ans=-1
for i in range(len(s)):
if(d[s[i]]==1):
ans=i
break
print(ans), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a string s, find the first non-repeating character in the string and return its index. If it does not exist, return -1.First line of the input contains the string s.
<b>Constraints</b>
1<= s. length <= 100000Print the index of the first non- repeating character in a stringInput
s = "newtonschool"
Output
1
Explanation
"e" is the first non- repeating character in a string, I have written this Solution Code: /**
* Author : tourist1256
* Time : 2022-01-10 12:51:16
**/
#include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
#define debug(...) 2351
#endif
int firstUniqChar(string s) {
map<char, int> charCount;
int len = s.length();
for (int i = 0; i < len; i++) {
charCount[s[i]]++;
}
for (int i = 0; i < len; i++) {
if (charCount[s[i]] == 1)
return i;
}
return -1;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
string str;
cin>>str;
cout<<firstUniqChar(str)<<"\n";
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer <b>N</b>, you need to typecast this integer to String. If the typecasting is done successfully then we will print "<b>Nice Job</b>" otherwise "<b>Wrong answer</b>".User task:
Since this is a functional problem you don't have to worry about the input. You just have to complete the function <b>checkConvertion()</b>, which contains N as a parameter.You need to return the typecasted string value. The driver code will print "<b>Nice Job</b>" otherwise "<b>Wrong answer</b>".Sample Input:
5
Sample Output:
Nice Job
Sample Input:
6
Sample Output:
Nice Job, I have written this Solution Code: def checkConevrtion(a):
return str(a)
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer <b>N</b>, you need to typecast this integer to String. If the typecasting is done successfully then we will print "<b>Nice Job</b>" otherwise "<b>Wrong answer</b>".User task:
Since this is a functional problem you don't have to worry about the input. You just have to complete the function <b>checkConvertion()</b>, which contains N as a parameter.You need to return the typecasted string value. The driver code will print "<b>Nice Job</b>" otherwise "<b>Wrong answer</b>".Sample Input:
5
Sample Output:
Nice Job
Sample Input:
6
Sample Output:
Nice Job, I have written this Solution Code: static String checkConevrtion(int a)
{
return String.valueOf(a);
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Please write a query to insert a comment into the database. The comment should be 'First comment' and it should be made by the user with the username 'newton'. The comment should be associated with the post that has a post_id of 2.
<schema>[{'name': 'post', 'columns': [{'name': 'id', 'type': 'int'}, {'name': 'username', 'type': 'varchar(24)'}, {'name': 'post_title', 'type': 'varchar (72)'}, {'name': 'post_description', 'type': 'text'}, {'name': 'datetime_created', 'type': 'datetime'}, {'name': 'number_of_likes', 'type': 'int'}, {'name': 'photo', 'type': 'blob'}]},{'name': 'comments', 'columns': [{'name': 'username', 'type': 'varchar(24)'}, {'name': 'comment_text', 'type': 'text'}, {'name': 'post_id', 'type': 'int'}]}]</schema>nannannan, I have written this Solution Code: INSERT INTO comment (username, comment_text, post_id) values ('newton', 'First comment', 2);, In this Programming Language: SQL, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Create a basic table namely TEST_TABLE with 1 field TEST_FIELD as int.
( USE ONLY UPPER CASE LETTERS )
<schema>[{'name': 'TEST_TABLE', 'columns': [{'name': 'TEST_FIELD', 'type': 'INT'}]}]</schema>nannannan, I have written this Solution Code: CREATE TABLE TEST_TABLE (
TEST_FIELD INT
);, In this Programming Language: SQL, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Find if the given sentence start with the given word1st line: Sentence
2nd line: Word which has to be in startPrint True or False if the sentence starts with the wordInput:
The world is small
The
Output:
True, I have written this Solution Code: import re
s=input()
w=input()
st="^"+w+".*"
x = re.search(st, s)
if(x):
print("True")
else:
print("False"), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: the user would give 5 words as input, print the position at which 'cricket' was given as input, it is assured that cricket was given as one of the 5 inputs.
position here is assumed to start from 1, so if cricket was the first input print 1, not 0.cricket
badminton
tennis
running
football1-, I have written this Solution Code: a= input()
b= input()
c= input()
d= input()
e= input()
li = [a,b,c,d,e]
print(li.index('cricket') + 1), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two integers x and y, check if x can be converted to y by adding F(n) to x where F(n){n>=1} is defined as:- 1+3+9+27+81+. .3^n.<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>Ifpossible()</b> that takes the integer x and y as parameter.
Constraints:-
1<= x < y <= 10^9Return 1 if it is possible to convert x into y else return 0.Sample Input:-
5 7
Sample Output:-
0
Sample Input:-
3 16
Sample Output:-
1
Explanation:-
F(3) = 1 + 3 + 9 = 13
3 + 13 = 16, I have written this Solution Code:
public static int Ifpossible(long x, long y){
long sum=y-x;
long ans=0;
long ch = 1;
while(ans<sum){
ans+=ch;
if(ans==sum){return 1;}
ch*=3;
}
return 0;
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two integers x and y, check if x can be converted to y by adding F(n) to x where F(n){n>=1} is defined as:- 1+3+9+27+81+. .3^n.<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>Ifpossible()</b> that takes the integer x and y as parameter.
Constraints:-
1<= x < y <= 10^9Return 1 if it is possible to convert x into y else return 0.Sample Input:-
5 7
Sample Output:-
0
Sample Input:-
3 16
Sample Output:-
1
Explanation:-
F(3) = 1 + 3 + 9 = 13
3 + 13 = 16, I have written this Solution Code:
int Ifpossible(long x, long y){
long sum=y-x;
long ans=0;
long ch = 1;
while(ans<sum){
ans+=ch;
if(ans==sum){return 1;break;}
ch*=(long)3;
}
return 0;
}
, In this Programming Language: C, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two integers x and y, check if x can be converted to y by adding F(n) to x where F(n){n>=1} is defined as:- 1+3+9+27+81+. .3^n.<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>Ifpossible()</b> that takes the integer x and y as parameter.
Constraints:-
1<= x < y <= 10^9Return 1 if it is possible to convert x into y else return 0.Sample Input:-
5 7
Sample Output:-
0
Sample Input:-
3 16
Sample Output:-
1
Explanation:-
F(3) = 1 + 3 + 9 = 13
3 + 13 = 16, I have written this Solution Code:
int Ifpossible(long x, long y){
long sum=y-x;
long ans=0;
long ch = 1;
while(ans<sum){
ans+=ch;
if(ans==sum){return 1;}
ch*=3;
}
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two integers x and y, check if x can be converted to y by adding F(n) to x where F(n){n>=1} is defined as:- 1+3+9+27+81+. .3^n.<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>Ifpossible()</b> that takes the integer x and y as parameter.
Constraints:-
1<= x < y <= 10^9Return 1 if it is possible to convert x into y else return 0.Sample Input:-
5 7
Sample Output:-
0
Sample Input:-
3 16
Sample Output:-
1
Explanation:-
F(3) = 1 + 3 + 9 = 13
3 + 13 = 16, I have written this Solution Code:
def Ifpossible(x,y) :
result = y-x
ans = 0
ch = 1
while ans<result :
ans+=ch
if ans==result:
return 1;
ch*=3
return 0;
, In this Programming Language: Python, 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: 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: Alexa will turn on the air conditioner if, and only if, the temperature of the room is 30 degrees Celsius or above. The current temperature of the room is X degrees Celsius. Will she turn on the air conditioner?The input consists of a single integer X.
<b>Constraints</b>
−40≤X≤40
X is an integer.Print Yes if you will turn on the air conditioner; print No otherwise.<b>Sample Input 1</b>
25
<b>Sample Output 1</b>
No
<b>Sample Input 2</b>
30
<b>Sample Output 2</b>
Yes, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
int main() {
int x;
cin >> x;
if (x >= 30) cout << "Yes\n"; else cout << "No\n";
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Everyone loves having chocolates. Saloni loves having chocolates more than anyone.
She has n bags having a[1], a[2], ..., a[n] number of chocolates. In one unit time, she can choose any bag a[i], eat all a[i] chocolates and then fill the bag with floor(a[i]/2) chocolates.
Find the maximum number of chocolates she can eat in k units of time.The first line of the input contains an integer n and k, the number of bags Saloni has and the units of time she will eat.
The second line of input contains n integers, the number of chocolates in ith bag.
Constraints
1 <= n, k <= 100000
1 <= a[i] <= 1000000000Output a single integer, the maximum number of chocolates she can have in k units of time.Sample Input
3 3
7 5 1
Sample Output
15
Explanation
In 1st unit time, she will eat from 1st bag (7 chocolates)
In 2nd unit time, she will eat from 2nd bag (5 chocolates)
In 3rd unit time, she will eat from 1st bag (3 chocolates), 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[] s=br.readLine().split(" ");
PriorityQueue<Integer> pq=new PriorityQueue<>(Collections.reverseOrder());
int n=Integer.parseInt(s[0]);
int k=Integer.parseInt(s[1]);
long max=0;
String[] str=br.readLine().split(" ");
for(int i=0;i<n;i++){
int cur=Integer.parseInt(str[i]);
pq.add(cur);
}
for(int i=0;i<k;i++){
int cur=pq.poll();
max+=cur;
pq.add(cur/2);
}
System.out.println(max);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Everyone loves having chocolates. Saloni loves having chocolates more than anyone.
She has n bags having a[1], a[2], ..., a[n] number of chocolates. In one unit time, she can choose any bag a[i], eat all a[i] chocolates and then fill the bag with floor(a[i]/2) chocolates.
Find the maximum number of chocolates she can eat in k units of time.The first line of the input contains an integer n and k, the number of bags Saloni has and the units of time she will eat.
The second line of input contains n integers, the number of chocolates in ith bag.
Constraints
1 <= n, k <= 100000
1 <= a[i] <= 1000000000Output a single integer, the maximum number of chocolates she can have in k units of time.Sample Input
3 3
7 5 1
Sample Output
15
Explanation
In 1st unit time, she will eat from 1st bag (7 chocolates)
In 2nd unit time, she will eat from 2nd bag (5 chocolates)
In 3rd unit time, she will eat from 1st bag (3 chocolates), 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 n, k; cin >> n >> k;
priority_queue<int> s;
for(int i = 1; i <= n; i++){
int p; cin >> p;
s.push(p);
}
int ans = 0;
while(k--){
int x = s.top();
s.pop();
ans += x;
s.push(x/2);
}
cout << ans;
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given a function <code>reverseString</code>, which takes in a string as a parameter. Your task is to complete the function such that it returns the reverse of the string.(hello changes to olleh)
// Complete the reverseString function
function reverseString(n) {
//Write Code Here
}A string nReturns the reverse of nconst n = 'hello'
reverseString(n) //displays 'olleh' in console, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
String n=sc.nextLine();
char tra[] = n.toCharArray();
for(int i=tra.length-1;i>=0;i--){
System.out.print(tra[i]);
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given a function <code>reverseString</code>, which takes in a string as a parameter. Your task is to complete the function such that it returns the reverse of the string.(hello changes to olleh)
// Complete the reverseString function
function reverseString(n) {
//Write Code Here
}A string nReturns the reverse of nconst n = 'hello'
reverseString(n) //displays 'olleh' in console, I have written this Solution Code: function reverseString (n) {
return n.split("").reverse().join("");
}, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an sorted array <b>Arr[]</b> of size <b>N</b>, containing both <b>negative</b> and <b>positive</b> integers, you need to print the squared sorted output.
<b>Note</b> Try using two pointer approachThe first line of input contains T, denoting the number of test cases. Each testcase contains 2 lines. The first line contains the N size of the array. The second line contains elements of an array separated by space.
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 10000
-10000 ≤ A[i] ≤ 10000
The Sum of N over all test cases does not exceed 10^6For each test case you need to print the sorted squared output in new lineInput:
1
5
-7 -2 3 4 6
Output:
4 9 16 36 49, I have written this Solution Code: import java.util.*;
import java.io.*;
class Main
{
public static void main(String[] args)throws IOException {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(read.readLine());
while (t-- > 0) {
int n = Integer.parseInt(read.readLine());
int[] arr = new int[n];
String str[] = read.readLine().trim().split(" ");
for(int i = 0; i < n; i++)
arr[i] = Integer.parseInt(str[i]);
arr = sortedSquares(arr);
for(int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
}
public static int[] sortedSquares(int[] A) {
int[] nums = new int[A.length];
int k=A.length-1;
int i=0, j=A.length-1;
while(i<=j){
if(Math.abs(A[i]) <= Math.abs(A[j])){
nums[k--] = A[j]*A[j];
j--;
}
else{
nums[k--] = A[i]*A[i];
i++;
}
}
return nums;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an sorted array <b>Arr[]</b> of size <b>N</b>, containing both <b>negative</b> and <b>positive</b> integers, you need to print the squared sorted output.
<b>Note</b> Try using two pointer approachThe first line of input contains T, denoting the number of test cases. Each testcase contains 2 lines. The first line contains the N size of the array. The second line contains elements of an array separated by space.
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 10000
-10000 ≤ A[i] ≤ 10000
The Sum of N over all test cases does not exceed 10^6For each test case you need to print the sorted squared output in new lineInput:
1
5
-7 -2 3 4 6
Output:
4 9 16 36 49, I have written this Solution Code: t = int(input())
for i in range(t):
n = int(input())
for i in sorted(map(lambda j:int(j)**2,input().split())):
print(i,end=' ')
print(), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: A balanced parentheses sequence is a sequence of parentheses such that each opening parenthesis has a matching closing parenthesis and the pairs of parentheses are properly nested. In other words, a balanced parentheses sequence must satisfy the following conditions:
The sequence is empty, or The sequence is of the form "(S)", where S is a balanced parentheses sequence, or The sequence is of the form "S1S2", where S1 and S2 are balanced parentheses sequences. For example, the following are balanced parentheses sequences:
""
"()"
"((()))"
"()()()"
"(()(()))"
And the following are not balanced parentheses sequences:
"("
")"
"()("
"(()"
"(()))"
"())("
Now, you are given two integers, A and B where A denotes the number of opening brackets i. e: ( and B denotes the number of closing brackets i. e: ). You need to report if you can build balanced parentheses using all of those brackets.The input consists of two space separated integers A and B.
<b>Constraints</b>
0 ≤ A, B ≤ 10^9Print "YES" (without quotes) if you can build a balanced parentheses using the given brackets, otherwise print "NO" (without quotes).<b>Sample Input 1</b>
2 1
<b>Sample Output 1</b>
NO
<b>Sample Input 2</b>
10 10
<b>Sample Output 2</b>
YES, I have written this Solution Code: #include"bits/stdc++.h"
using namespace std;
signed main() {
int x,y;
cin>>x>>y;
if(x==y)cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: A group of contest writers have written n problems and want to use k of them in an upcoming
contest. Each problem has a difficulty level. A contest is valid if all of its k problems have different
difficulty levels.
Compute how many distinct valid contests the contest writers can produce. Two contests are
distinct if and only if there exists some problem present in one contest but not present in the other.
Print the result modulo 998244353.The first line of input contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 1000).
The next line contains n space-separated integers representing the difficulty levels. The difficulty
levels are between 1 and 10^9
(inclusive).Print the number of distinct contests possible, modulo 998244353Sample input
5 2
1 2 3 4 5
Sample output
10
Sample input
5 2
1 1 1 2 2
Sample output
6, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) {
Scanner inputTaker = new Scanner(System.in);
int N = inputTaker.nextInt();
int K = inputTaker.nextInt();
HashMap<Long,Integer> map= new HashMap<>();
for(int i =0; i < N ; i++)
{
long temp = inputTaker.nextLong();
int count = 1;
if(map.containsKey(temp))
count += map.get(temp);
map.put(temp,count);
}
int a[] = new int[map.size()];
int i = 0;
for(Long k : map.keySet()) {
a[i] = map.get(k);
i++;
}
long dp[][] = new long[K+1][a.length + 1];
for(int j = 0; j < K+1; j++)
for(int k = 0; k < a.length + 1; k++) {
dp[j][k] = -1L;
}
System.out.print(f( a, K, 0,dp));
}
public static long f(int[] a, int k, int i,long[][] dp) {
int n = a.length;
if(k > n - i) {
return 0;
}
if(k == 0) {
return 1;
}
if(dp[k][i] != -1)
return dp[k][i];
return dp[k][i] = (a[i] * f(a, k - 1, i + 1,dp) % 998244353 + f(a, k, i + 1,dp)) % 998244353;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: A group of contest writers have written n problems and want to use k of them in an upcoming
contest. Each problem has a difficulty level. A contest is valid if all of its k problems have different
difficulty levels.
Compute how many distinct valid contests the contest writers can produce. Two contests are
distinct if and only if there exists some problem present in one contest but not present in the other.
Print the result modulo 998244353.The first line of input contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 1000).
The next line contains n space-separated integers representing the difficulty levels. The difficulty
levels are between 1 and 10^9
(inclusive).Print the number of distinct contests possible, modulo 998244353Sample input
5 2
1 2 3 4 5
Sample output
10
Sample input
5 2
1 1 1 2 2
Sample output
6, I have written this Solution Code: from collections import Counter
mod = 998244353
n,k = map(int, input().split())
c = Counter(map(int, input().split()))
if len(c)<k:
print('0')
else:
poly = [1]
for v in c.values():
npoly = poly[:]
npoly.append(0)
for i in range(len(poly)):
npoly[i+1] = (npoly[i+1] + v * poly[i]) % mod
poly = npoly[:k+1]
print(poly[k]), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: A group of contest writers have written n problems and want to use k of them in an upcoming
contest. Each problem has a difficulty level. A contest is valid if all of its k problems have different
difficulty levels.
Compute how many distinct valid contests the contest writers can produce. Two contests are
distinct if and only if there exists some problem present in one contest but not present in the other.
Print the result modulo 998244353.The first line of input contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 1000).
The next line contains n space-separated integers representing the difficulty levels. The difficulty
levels are between 1 and 10^9
(inclusive).Print the number of distinct contests possible, modulo 998244353Sample input
5 2
1 2 3 4 5
Sample output
10
Sample input
5 2
1 1 1 2 2
Sample output
6, I have written this Solution Code: #include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int mod = 998244353;
int a[1010];
ll val[1010];
ll dp[1010][1010];
int main()
{
int n, k;
cin >> n >> k;
for(int i = 1; i <= n; ++ i)
{
scanf("%d", &a[i]);
}
sort(a + 1, a + 1 + n);
int cnt = 1;
int top = 1;
for(int i = 2; i <= n; ++ i)
{
if(a[i] == a[i - 1])
cnt++;
else
{
val[top++] = cnt;
cnt = 1;
}
}
val[top++] = cnt;
memset(dp, 0, sizeof(dp));
for(int i = 0; i <= 1000; ++ i)
dp[i][0] = 1;
for(int i = 1; i < top; ++ i)
{
for(int j = 1; j <= k; ++ j)
{
dp[i][j] = (dp[i - 1][j - 1] * val[i] % mod + dp[i - 1][j]) % mod;
}
}
cout << dp[top - 1][k] << 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 integers. Find the product of maximum values for every subarray of size K. Print the answer modulo 10<sup>9</sup>+7.
A subarray is any contiguous sequence of elements in an array.The first line contains two integers N and K, denoting the size of the array and the size of the subarray respectively.
The next line contains N integers denoting the elements of the array.
<b>Constarints</b>
1 <= K <= N <= 1000000
1 <= A[i] <= 1000000Print a single integer denoting the product of maximums for every subarray of size K modulo 1000000007Sample Input 1:
6 4
1 5 2 3 6 4
Sample Output 1:
180
<b>Explanation:</b>
For subarray [1, 5, 2, 3], maximum = 5
For subarray [5, 2, 3, 6], maximum = 6
For subarray [2, 3, 6, 4], maximum = 6
Therefore, ans = 5*6*6 = 180, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args)throws IOException {
Reader sc=new Reader();
int n=sc.nextInt();
int b=sc.nextInt();
int[] a=new int[n];
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
}
int j, max;
long mul=1;
Deque<Integer> dq= new LinkedList<Integer>();
for (int i = 0;i<b;i++)
{
while (!dq.isEmpty() && a[i] >=a[dq.peekLast()])
dq.removeLast();
dq.addLast(i);
}
mul=((mul%1000000007)*(a[dq.peek()]%1000000007))%1000000007;
for (int i=b; i < n;i++)
{
while ((!dq.isEmpty()) && dq.peek() <=i-b)
dq.removeFirst();
while ((!dq.isEmpty()) && a[i]>=a[dq.peekLast()])
dq.removeLast();
dq.addLast(i);
mul=((mul%1000000007)*(a[dq.peek()]%1000000007))%1000000007;
}
System.out.println(mul%1000000007);
}
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')
break;
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();
}
}
}, 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 integers. Find the product of maximum values for every subarray of size K. Print the answer modulo 10<sup>9</sup>+7.
A subarray is any contiguous sequence of elements in an array.The first line contains two integers N and K, denoting the size of the array and the size of the subarray respectively.
The next line contains N integers denoting the elements of the array.
<b>Constarints</b>
1 <= K <= N <= 1000000
1 <= A[i] <= 1000000Print a single integer denoting the product of maximums for every subarray of size K modulo 1000000007Sample Input 1:
6 4
1 5 2 3 6 4
Sample Output 1:
180
<b>Explanation:</b>
For subarray [1, 5, 2, 3], maximum = 5
For subarray [5, 2, 3, 6], maximum = 6
For subarray [2, 3, 6, 4], maximum = 6
Therefore, ans = 5*6*6 = 180, I have written this Solution Code: from collections import deque
deq=deque()
n,k=list(map(int,input().split()))
array=list(map(int,input().split()))
for i in range(k):
while(deq and array[deq[-1]]<=array[i]):
deq.pop()
deq.append(i)
ans=1
for j in range(k,n):
ans=ans*array[deq[0]]
ans=(ans)%1000000007
while(deq and deq[0]<=j-k):
deq.popleft()
while(deq and array[deq[-1]]<=array[j]):
deq.pop()
deq.append(j)
ans=ans*array[deq[0]]
ans=(ans)%1000000007
print(ans), 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 integers. Find the product of maximum values for every subarray of size K. Print the answer modulo 10<sup>9</sup>+7.
A subarray is any contiguous sequence of elements in an array.The first line contains two integers N and K, denoting the size of the array and the size of the subarray respectively.
The next line contains N integers denoting the elements of the array.
<b>Constarints</b>
1 <= K <= N <= 1000000
1 <= A[i] <= 1000000Print a single integer denoting the product of maximums for every subarray of size K modulo 1000000007Sample Input 1:
6 4
1 5 2 3 6 4
Sample Output 1:
180
<b>Explanation:</b>
For subarray [1, 5, 2, 3], maximum = 5
For subarray [5, 2, 3, 6], maximum = 6
For subarray [2, 3, 6, 4], maximum = 6
Therefore, ans = 5*6*6 = 180, I have written this Solution Code: #include<bits/stdc++.h>
#define int long long
#define ll long long
#define pb push_back
#define endl '\n'
#define pii pair<int,int>
#define vi vector<int>
#define all(a) (a).begin(),(a).end()
#define F first
#define S second
#define sz(x) (int)x.size()
#define hell 1000000007
#define rep(i,a,b) for(int i=a;i<b;i++)
#define dep(i,a,b) for(int i=a;i>=b;i--)
#define lbnd lower_bound
#define ubnd upper_bound
#define bs binary_search
#define mp make_pair
using namespace std;
const int N = 1e6 + 5;
const int mod = 1e9 + 7;
const int inf = 1e9 + 9;
int a[N];
void solve(){
int n, k;
cin >> n >> k;
for(int i = 1; i <= n; i++)
cin >> a[i];
deque<int> q;
for(int i = 1; i <= k; i++){
while(!q.empty() && a[q.back()] <= a[i])
q.pop_back();
q.push_back(i);
}
int ans = a[q.front()];
for(int i = k+1; i <= n; i++){
if(q.front() == i-k)
q.pop_front();
while(!q.empty() && a[q.back()] <= a[i])
q.pop_back();
q.push_back(i);
ans = (ans*a[q.front()]) % mod;
}
cout << ans;
}
void testcases(){
int tt = 1;
//cin >> tt;
while(tt--){
solve();
}
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
clock_t start = clock();
testcases();
cerr << (double)(clock() - start)*1000/CLOCKS_PER_SEC << " ms: ";
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: There is a directed graph of N nodes and M edges with each node labeled from 0 to N - 1.
A node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node. Find the number of safe nodes.First line contains two integers N and M denoting the number of nodes and number of edges.
Then M lines follow each containing two integers u and v denoting there is an edge from node u to node v.
Constraints
1 <= N <= 10^4
1<= M <= 10^4
0 <= u,v < N
The graph may contain self- loops.Print the number of safe nodes.Sample Input 1:
7 7
0 1
0 2
1 2
1 3
2 5
3 0
4 5
Output
4
Explanation:
Nodes 5 and 6 are terminal nodes as there are no outgoing edges from either of them.
Every path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6.
Sample Input 2:
5 10
0 1
0 2
0 3
0 4
1 1
1 2
2 3
2 4
3 0
3 4
Output
1
Explanation:
Only node 4 is a terminal node, and every path starting at node 4 leads to node 4., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main{
static int eventualSafeNodes(ArrayList<ArrayList<Integer>> graph) {
//count outgoing edges
int nr=graph.size();
int[] outdegree = new int[nr];
//graph
Map<Integer, Set<Integer>> map = new HashMap();
Queue<Integer> queue = new LinkedList();
List<Integer> res = new LinkedList();
for (int i = 0; i < nr; i++) {
ArrayList<Integer> edges = graph.get(i);
// make graph
for (int edge : edges) {
if (!map.containsKey(edge))
map.put(edge, new HashSet());
//map in reverse way
// 1->0, 2->0, 2-1, 3->1.....
map.get(edge).add(i);
}
//no. of outgoing edges
outdegree[i] = edges.size();
//safe states
if (outdegree[i] == 0)
queue.offer(i);
}
// System.out.println(map);
while (!queue.isEmpty()) {
int node = queue.poll();
//edges to node
if (map.containsKey(node)) {
Set<Integer> release = map.get(node);
for (int n : release) {
//decrease outdegre of edges which can reach node
//as we remove node
outdegree[n]--;
//if some state becomes safe add it to the queue
if (outdegree[n] == 0)
queue.offer(n);
}
}
}
// we have to return in ascending order
// so we add safe states at the end
for (int i = 0; i < outdegree.length; i++) {
if (outdegree[i] == 0)
res.add(i);
}
return res.size();
}
public static void main (String[] args)throws IOException {
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
String line = br.readLine();
String[] strs = line.trim().split("\\s+");
int n=Integer.parseInt(strs[0]);
int m=Integer.parseInt(strs[1]);
ArrayList<ArrayList<Integer> > g = new ArrayList<ArrayList<Integer> >(n);
for(int i=0;i<n;i++){
ArrayList<Integer> x = new ArrayList<Integer>();
g.add(x);
}
for(int i=0;i<m;i++){
line = br.readLine();
strs = line.trim().split("\\s+");
int x=Integer.parseInt(strs[0]);
int y=Integer.parseInt(strs[1]);
g.get(x).add(y);
}
System.out.print(eventualSafeNodes(g));
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: A tuple (R, G, B) is considered good if R*G+B <= N and R, G and B are all positive. Given N, find number of good tuples.Input contains a single integer N.
Constraints:
1 <= N <= 1000000Print number of good tuples.Sample Input
3
Sample Output
4
Explanation:
Following are the good tuples:
(1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(2, 1, 1), I have written this Solution Code: import java.util.*;
import java.io.*;
class Main{
public static void main(String[] args)throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
long count=0;
for(int i=1;i<n;i++){
int t=n-i;
while(t>=1){
count+=t;
t=t-i;
}
}
System.out.println(count);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: A tuple (R, G, B) is considered good if R*G+B <= N and R, G and B are all positive. Given N, find number of good tuples.Input contains a single integer N.
Constraints:
1 <= N <= 1000000Print number of good tuples.Sample Input
3
Sample Output
4
Explanation:
Following are the good tuples:
(1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(2, 1, 1), I have written this Solution Code: n = int(input())
m = n-1
count = 0
for r in range(1, n):
c = m//r
count += c*(n-r*c) + r*c*(c-1)//2
print(count), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.