Instruction
stringlengths 261
35k
| Response
stringclasses 1
value |
---|---|
For this Question: Harry wants to rescue Fleur's sister Gabrielle in the underwater task. For that he needs to get ahead of all the people in the two magical queues.
Our small Tono and Solo are busy casting spells alternatively to remove people from the two magical queues. But since they are highly competitive, both of them wish to be the last person to remove people from the queue.
We can consider the removal of people as game played between Tono and Solo with the following rules:
<li> The turn goes alternatively. Tono starts the game.
<li> In each turn, the player first chooses a queue, then removes 3*X people from the queue, and then adds X people to the other queue (X > 0).
<li> The player who is unable to make a move loses.
<li> Both the players play with the most optimal strategy.
Since this game can take a lot of time to complete, Harry can declare the last person to remove people from the queue directly. Can you please help Harry accomplish the task, and save Gabrielle by being on time?The first line of the input contains an integer T denoting the number of test cases.
The next T lines contains two integers L1 and L2, denoting the initial number of people standing in the two queues.
Constraints
1 <= T <= 100
1 <= L1, L2 <= 200000For each test case, output "Tono" (without quotes) if Tono wins the game, else output "Solo" (without quotes) in a new line.Sample Input
2
0 1
0 2
Sample Output
Solo
Solo
Explanation
For both test cases, since Tono cannot make any move in the first turn itself, she loses.
Sample Input
1
1 4
Sample Output
Tono
Explanation
Tono removes 3 people from second queue, and adds 1 in the first queue. The queues now have 2 and 1 people respectively. Since Solo cannot make a move now, she loses., 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 l1, l2; cin>>l1>>l2;
assert(l1<=200000 && l2<=200000);
if(abs(l1-l2)<2){
cout<<"Solo";
return;
}
else if(abs(l1-l2)>=3){
cout<<"Tono";
return;
}
if(l1%2){
cout<<"Tono";
}
else{
cout<<"Solo";
}
}
signed main()
{
fast
#ifdef SWAPNIL07
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int t=1;
cin>>t;
while(t--){
solve();
cout<<"\n";
}
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a sorted array arr[] of N integers and a number K is given. The task is to check if the element K is present in the array or not.
<b>Note:</b> Use binary search to solve the problemThe first line of input contains a number of test cases T. For each test case, the first line of input contains a number of elements in the array, and the number K is separated by space. The next line contains N elements.
<b>Constraints:</b>
1 ≤ T ≤ 10
1 ≤ N ≤ 10<sup>5</sup>
1 ≤ K ≤ 10<sup>9</sup>
1 ≤ arr[i] ≤ 10<sup>9</sup>
<b>Sum of N over all test cases doesn't exceed 10<sup>6</sup></b>If the element is present in the array print "1" else print "-1".Sample Input:
2
5 6
1 2 3 4 6
5 2
1 3 4 5 6
Sample Output:
1
-1, I have written this Solution Code: static int isPresent(long arr[], int n, long k)
{
int left = 0;
int right = n-1;
int res = -1;
while(left<=right){
int mid = (left+right)/2;
if(arr[mid] == k){
res = 1;
break;
}else if(arr[mid] < k){
left = mid + 1;
}else{
right = mid - 1;
}
}
return res;
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a sorted array arr[] of N integers and a number K is given. The task is to check if the element K is present in the array or not.
<b>Note:</b> Use binary search to solve the problemThe first line of input contains a number of test cases T. For each test case, the first line of input contains a number of elements in the array, and the number K is separated by space. The next line contains N elements.
<b>Constraints:</b>
1 ≤ T ≤ 10
1 ≤ N ≤ 10<sup>5</sup>
1 ≤ K ≤ 10<sup>9</sup>
1 ≤ arr[i] ≤ 10<sup>9</sup>
<b>Sum of N over all test cases doesn't exceed 10<sup>6</sup></b>If the element is present in the array print "1" else print "-1".Sample Input:
2
5 6
1 2 3 4 6
5 2
1 3 4 5 6
Sample Output:
1
-1, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
unordered_map<long long,int> m;
long k;
cin>>k;
long long a;
for(int i=0;i<n;i++){
cin>>a;
m[a]++;
}
if(m.find(k)!=m.end()){
cout<<1<<endl;
}
else{
cout<<-1<<endl;
}
}
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a sorted array arr[] of N integers and a number K is given. The task is to check if the element K is present in the array or not.
<b>Note:</b> Use binary search to solve the problemThe first line of input contains a number of test cases T. For each test case, the first line of input contains a number of elements in the array, and the number K is separated by space. The next line contains N elements.
<b>Constraints:</b>
1 ≤ T ≤ 10
1 ≤ N ≤ 10<sup>5</sup>
1 ≤ K ≤ 10<sup>9</sup>
1 ≤ arr[i] ≤ 10<sup>9</sup>
<b>Sum of N over all test cases doesn't exceed 10<sup>6</sup></b>If the element is present in the array print "1" else print "-1".Sample Input:
2
5 6
1 2 3 4 6
5 2
1 3 4 5 6
Sample Output:
1
-1, I have written this Solution Code: def binary_search(arr, low, high, x):
if high >= low:
mid = (high + low) // 2
if arr[mid] == x:
return 1
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
else:
return binary_search(arr, mid + 1, high, x)
else:
return -1
def position(n,arr,x):
return binary_search(arr,0,n-1,x)
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a sorted array arr[] of N integers and a number K is given. The task is to check if the element K is present in the array or not.
<b>Note:</b> Use binary search to solve the problemThe first line of input contains a number of test cases T. For each test case, the first line of input contains a number of elements in the array, and the number K is separated by space. The next line contains N elements.
<b>Constraints:</b>
1 ≤ T ≤ 10
1 ≤ N ≤ 10<sup>5</sup>
1 ≤ K ≤ 10<sup>9</sup>
1 ≤ arr[i] ≤ 10<sup>9</sup>
<b>Sum of N over all test cases doesn't exceed 10<sup>6</sup></b>If the element is present in the array print "1" else print "-1".Sample Input:
2
5 6
1 2 3 4 6
5 2
1 3 4 5 6
Sample Output:
1
-1, I have written this Solution Code: // arr is they array to search from
// x is target
function binSearch(arr, x) {
// write code here
// do not console.log
// return the 1 or -1
let l = 0;
let r = arr.length - 1;
let mid;
while (r >= l) {
mid = l + Math.floor((r - l) / 2);
// If the element is present at the middle
// itself
if (arr[mid] == x)
return 1;
// If element is smaller than mid, then
// it can only be present in left subarray
if (arr[mid] > x)
r = mid - 1;
// Else the element can only be present
// in right subarray
else
l = mid + 1;
}
// We reach here when element is not
// present in array
return -1;
}, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array A[], of size N containing positive integers. You need to print the elements of an array in increasing order.The first line of the input denotes the number of test cases 'T'. The first line of the test case is the size of the array and the second line consists of array elements.
For Python Users just complete the given function.
<b>Constraints:</b>
1 ≤ T ≤ 100
1 ≤ N ≤ 1000
1 ≤ A[i] ≤ 1000For each testcase print the sorted array in a new line.Input:
2
5
4 1 3 9 7
10
10 9 8 7 6 5 4 3 2 1
Output:
1 3 4 7 9
1 2 3 4 5 6 7 8 9 10
<b>Explanation:</b>
Testcase 1: 1 3 4 7 9 are in sorted form.
Testcase 2: For the given input, 1 2 3 4 5 6 7 8 9 10 are in sorted form., I have written this Solution Code: #include "bits/stdc++.h"
#pragma GCC optimize "03"
using namespace std;
#define int long long int
#define ld long double
#define pi pair<int, int>
#define pb push_back
#define fi first
#define se second
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#ifndef LOCAL
#define endl '\n'
#endif
const int N = 2e5 + 5;
const int mod = 1e9 + 7;
const int inf = 1e9 + 9;
int a[N];
signed main() {
IOS;
int t; cin >> t;
while(t--){
int n; cin >> n;
for(int i = 1; i <= n; i++)
cin >> a[i];
sort(a + 1, a + n + 1);
for(int i = 1; i <= n; i++)
cout << a[i] << " ";
cout << 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 size N containing positive integers. You need to print the elements of an array in increasing order.The first line of the input denotes the number of test cases 'T'. The first line of the test case is the size of the array and the second line consists of array elements.
For Python Users just complete the given function.
<b>Constraints:</b>
1 ≤ T ≤ 100
1 ≤ N ≤ 1000
1 ≤ A[i] ≤ 1000For each testcase print the sorted array in a new line.Input:
2
5
4 1 3 9 7
10
10 9 8 7 6 5 4 3 2 1
Output:
1 3 4 7 9
1 2 3 4 5 6 7 8 9 10
<b>Explanation:</b>
Testcase 1: 1 3 4 7 9 are in sorted form.
Testcase 2: For the given input, 1 2 3 4 5 6 7 8 9 10 are in sorted form., I have written this Solution Code: // arr is unsorted array
// n is the number of elements in the array
function bubbleSort(arr, n) {
// write code here
// do not console.log the answer
// return sorted array
return arr.sort((a, b) => a - b)
}, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array A[], of size N containing positive integers. You need to print the elements of an array in increasing order.The first line of the input denotes the number of test cases 'T'. The first line of the test case is the size of the array and the second line consists of array elements.
For Python Users just complete the given function.
<b>Constraints:</b>
1 ≤ T ≤ 100
1 ≤ N ≤ 1000
1 ≤ A[i] ≤ 1000For each testcase print the sorted array in a new line.Input:
2
5
4 1 3 9 7
10
10 9 8 7 6 5 4 3 2 1
Output:
1 3 4 7 9
1 2 3 4 5 6 7 8 9 10
<b>Explanation:</b>
Testcase 1: 1 3 4 7 9 are in sorted form.
Testcase 2: For the given input, 1 2 3 4 5 6 7 8 9 10 are in sorted form., 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 t = sc.nextInt();
while(t-->0){
int n = sc.nextInt();
int a[] = new int[n];
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
}
int temp;
for(int i=1;i<n;i++){
if(a[i]<a[i-1]){
for(int j=i;j>0;j--){
if(a[j]<a[j-1]){
temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;
}
else{
break;
}
}
}
}
for(int i=0;i<n;i++){
System.out.print(a[i]+" ");
}
System.out.println();
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array A[], of size N containing positive integers. You need to print the elements of an array in increasing order.The first line of the input denotes the number of test cases 'T'. The first line of the test case is the size of the array and the second line consists of array elements.
For Python Users just complete the given function.
<b>Constraints:</b>
1 ≤ T ≤ 100
1 ≤ N ≤ 1000
1 ≤ A[i] ≤ 1000For each testcase print the sorted array in a new line.Input:
2
5
4 1 3 9 7
10
10 9 8 7 6 5 4 3 2 1
Output:
1 3 4 7 9
1 2 3 4 5 6 7 8 9 10
<b>Explanation:</b>
Testcase 1: 1 3 4 7 9 are in sorted form.
Testcase 2: For the given input, 1 2 3 4 5 6 7 8 9 10 are in sorted form., I have written this Solution Code: def bubbleSort(arr):
arr.sort()
return arr
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer N, find the closest prime number to N. If there are multiple print the smaller one.The input contains a single integer N.
Constraints:
1 <= N <= 1000000000Print the closest prime to N.Sample Input 1
12
Sample Output 1
11
Explanation: Closest prime to 12 is 11 and 13 smaller of which is 11.
Sample Input 2
17
Sample Output 2
17
Explanation: Closest prime to 17 is 17., 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());
if(n==1){
System.out.println(2);
}else{
int after = afterPrime(n);
int before = beforePrime(n);
if(before>after){
System.out.println(n+after);
}
else{System.out.println(n-before);}
}
}
public static boolean isPrime(int n)
{
int count=0;
for(int i=2;i*i<n;i++)
{
if(n%i==0)
count++;
}
if(count==0)
return true;
else
return false;
}
public static int beforePrime(int n)
{
int c=0;
while(true)
{
if(isPrime(n))
return c;
else
{
n=n-1;
c++;
}
}
}
public static int afterPrime(int n)
{
int c=0;
while(true)
{
if(isPrime(n))
return c;
else
{
n=n+1;
c++;
}
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer N, find the closest prime number to N. If there are multiple print the smaller one.The input contains a single integer N.
Constraints:
1 <= N <= 1000000000Print the closest prime to N.Sample Input 1
12
Sample Output 1
11
Explanation: Closest prime to 12 is 11 and 13 smaller of which is 11.
Sample Input 2
17
Sample Output 2
17
Explanation: Closest prime to 17 is 17., I have written this Solution Code: from math import sqrt
def NearPrime(N):
if N >1:
for i in range(2,int(sqrt(N))+1):
if N%i ==0:
return False
break
else: return True
else: return False
N=int(input())
i =0
while NearPrime(N-i)==False and NearPrime(N+i)==False:
i+=1
if NearPrime(N-i) and NearPrime(N+i):print(N-i)
elif NearPrime(N-i):print(N-i)
elif NearPrime(N+i): print(N+i), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer N, find the closest prime number to N. If there are multiple print the smaller one.The input contains a single integer N.
Constraints:
1 <= N <= 1000000000Print the closest prime to N.Sample Input 1
12
Sample Output 1
11
Explanation: Closest prime to 12 is 11 and 13 smaller of which is 11.
Sample Input 2
17
Sample Output 2
17
Explanation: Closest prime to 17 is 17., 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>
/////////////
bool isPrime(int n){
if(n<=1)
return false;
for(int i=2;i*i<=n;++i)
if(n%i==0)
return false;
return true;
}
signed main()
{
fastio;
#ifdef ANIKET_GOYAL
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
int n;
cin>>n;
if(n==1)
cout<<"2";
else{
int v1=n,v2=n;
while(isPrime(v1)==false)
--v1;
while(isPrime(v2)==false)
++v2;
if(v2-n==n-v1)
cout<<v1;
else{
if(v2-n<n-v1)
cout<<v2;
else
cout<<v1;
}
}
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Bob has an array of N numbers. He wants to calculate the product of the array but does not want integers greater than 10<sup>18</sup>. So, if the result exceeds 10<sup>18</sup>, print -1 instead.<b>Constraints:</b>
2 ≤ N ≤ 10<sup>5</sup>
0 ≤ A<sub>i</sub> ≤ 10<sup>18</sup>
All values in the input are integers.Print the value of A<sub>1</sub>×A<sub>2</sub>....×A<sub>N</sub> as an integer, or -1 if the value exceeds 10<sup>18</sup>.Sample Input 1
2
1000000000 1000000000
Sample Output 1
1000000000000000000
Sample Input 2
3
101 9901 999999000001
Sample Output 2
-1
<b>Explanation</b>
We have 1000000000×1000000000=1000000000000000000.
We have 101×9901×999999000001=1000000000000000001, which exceeds 10<sup>18</sup>, so we should print -1 instead., I have written this Solution Code:
a = int(input())
ls = list(input().split())
temp=1
fl=0
for x in range(a):
if(int(ls[x])==0):
print(0)
fl=1
break
if(fl==0):
for y in range(a):
temp = temp*int(ls[y])
if(temp>1000000000000000000):
print(-1)
break
if(temp<1000000000000000000):
print(temp), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Bob has an array of N numbers. He wants to calculate the product of the array but does not want integers greater than 10<sup>18</sup>. So, if the result exceeds 10<sup>18</sup>, print -1 instead.<b>Constraints:</b>
2 ≤ N ≤ 10<sup>5</sup>
0 ≤ A<sub>i</sub> ≤ 10<sup>18</sup>
All values in the input are integers.Print the value of A<sub>1</sub>×A<sub>2</sub>....×A<sub>N</sub> as an integer, or -1 if the value exceeds 10<sup>18</sup>.Sample Input 1
2
1000000000 1000000000
Sample Output 1
1000000000000000000
Sample Input 2
3
101 9901 999999000001
Sample Output 2
-1
<b>Explanation</b>
We have 1000000000×1000000000=1000000000000000000.
We have 101×9901×999999000001=1000000000000000001, which exceeds 10<sup>18</sup>, so we should print -1 instead., I have written this Solution Code: #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define f(i,p,q) for(long long int i=p;i<q;i++)
void solve(){
ll n,m=1,x=0;
cin>>n;
vector<ll> a(n);
f(i,0,n) cin>>a[i];
ll k=pow(10,18);
ll p=k;
sort(a.begin(),a.end());
reverse(a.begin(),a.end());
f(i,0,n-1){
p/=a[i];
m*=a[i];
}
if(p<a[n-1]) cout<<-1<<endl;
else cout<<m*a[n-1]<<endl;
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
//ll t;
//cin>>t;
//while(t--)
solve();
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Bob has an array of N numbers. He wants to calculate the product of the array but does not want integers greater than 10<sup>18</sup>. So, if the result exceeds 10<sup>18</sup>, print -1 instead.<b>Constraints:</b>
2 ≤ N ≤ 10<sup>5</sup>
0 ≤ A<sub>i</sub> ≤ 10<sup>18</sup>
All values in the input are integers.Print the value of A<sub>1</sub>×A<sub>2</sub>....×A<sub>N</sub> as an integer, or -1 if the value exceeds 10<sup>18</sup>.Sample Input 1
2
1000000000 1000000000
Sample Output 1
1000000000000000000
Sample Input 2
3
101 9901 999999000001
Sample Output 2
-1
<b>Explanation</b>
We have 1000000000×1000000000=1000000000000000000.
We have 101×9901×999999000001=1000000000000000001, which exceeds 10<sup>18</sup>, so we should print -1 instead., I have written this Solution Code: import java.io.*;
import java.util.*;
import java.math.BigInteger;
class Main {
public static boolean search0 (int index,String [] arr){
for(int i =index;i<arr.length;i++){
if(arr[i].equals("0")){
System.out.println(0);
return true;
}
}
return false;
}
public static void main (String[] args)throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String [] arr = br.readLine().split(" ");
BigInteger limit = new BigInteger("1000000000000000000");
BigInteger result = BigInteger.ONE;
int i =0;
for( i=0; i<n;i++){
result = result.multiply(new BigInteger(arr[i]));
if(result.compareTo(limit)>0){
if(search0(i+1,arr)){
break;
};
System.out.println("-1");
break;
}
}
if(i==n){
System.out.println(result);
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Find out all the names in the given sentence (Note names must be greater than 2 characters)Sentence or paragraphList of namesInput:
Hi I am Ram
Output:
['Ram'], I have written this Solution Code: import re
st=input()
pattern="[A-Z][a-z]{2,100}"
l=re.findall(pattern,st)
print(l)
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given two arrays - value and frequency both containing N elements.
There is also a third array C which is currently empty. Then you perform N insertion operation in the array. For ith operation you insert value[i] to the end of the array frequency[i] number of times.
Finally you have to tell the kth smallest element in the array C.First line of input contains N.
Second line contains N integers denoting array - value
Third line contains N integers denoting array - frequency
Fourth line contains single integer K.
Constraints
1 <= N, value[i], frequency[i] <= 100000
1 <= k <= frequency[1] + frequency[2] +frequency[3] +........ + frequency[N]
Output a single integer which is the kth smallest element of the array C.Sample input 1
5
1 2 3 4 5
1 1 1 2 2
3
Sample output 1
3
Explanation 1:
Array C constructed is 1 2 3 4 4 5 5
Third smallest element is 3
Sample input 2
3
2 1 3
3 3 2
2
sample output 2
1
Explanation 2:
Array C constructed is 2 2 2 1 1 1 3 3
Second smallest element is 1, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args)throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
int[] val = new int[n];
for(int i=0; i<n; i++){
val[i] = Integer.parseInt(st.nextToken());
}
st = new StringTokenizer(br.readLine());
int[] freq = new int[n];
for(int i=0; i<n; i++){
freq[i] = Integer.parseInt(st.nextToken());
}
int k = Integer.parseInt(br.readLine());
for (int i=0; i<n; i++) {
for (int j=i+1; j<n; j++) {
if (val[j] < val[i]) {
int temp = val[i];
val[i] = val[j];
val[j] = temp;
int temp1 = freq[i];
freq[i] = freq[j];
freq[j] = temp1;
}
}
}
int element=0;
for(int i=0; i<n; i++){
for(int j=0; j<freq[i]; j++){
element++;
int value = val[i];
if(element==k){
System.out.print(value);
break;
}
}
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given two arrays - value and frequency both containing N elements.
There is also a third array C which is currently empty. Then you perform N insertion operation in the array. For ith operation you insert value[i] to the end of the array frequency[i] number of times.
Finally you have to tell the kth smallest element in the array C.First line of input contains N.
Second line contains N integers denoting array - value
Third line contains N integers denoting array - frequency
Fourth line contains single integer K.
Constraints
1 <= N, value[i], frequency[i] <= 100000
1 <= k <= frequency[1] + frequency[2] +frequency[3] +........ + frequency[N]
Output a single integer which is the kth smallest element of the array C.Sample input 1
5
1 2 3 4 5
1 1 1 2 2
3
Sample output 1
3
Explanation 1:
Array C constructed is 1 2 3 4 4 5 5
Third smallest element is 3
Sample input 2
3
2 1 3
3 3 2
2
sample output 2
1
Explanation 2:
Array C constructed is 2 2 2 1 1 1 3 3
Second smallest element is 1, I have written this Solution Code: def myFun():
n = int(input())
arr1 = list(map(int,input().strip().split()))
arr2 = list(map(int,input().strip().split()))
k = int(input())
arr = []
for i in range(n):
arr.append((arr1[i], arr2[i]))
arr.sort()
c = 0
for i in arr:
k -= i[1]
if k <= 0:
print(i[0])
return
myFun()
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given two arrays - value and frequency both containing N elements.
There is also a third array C which is currently empty. Then you perform N insertion operation in the array. For ith operation you insert value[i] to the end of the array frequency[i] number of times.
Finally you have to tell the kth smallest element in the array C.First line of input contains N.
Second line contains N integers denoting array - value
Third line contains N integers denoting array - frequency
Fourth line contains single integer K.
Constraints
1 <= N, value[i], frequency[i] <= 100000
1 <= k <= frequency[1] + frequency[2] +frequency[3] +........ + frequency[N]
Output a single integer which is the kth smallest element of the array C.Sample input 1
5
1 2 3 4 5
1 1 1 2 2
3
Sample output 1
3
Explanation 1:
Array C constructed is 1 2 3 4 4 5 5
Third smallest element is 3
Sample input 2
3
2 1 3
3 3 2
2
sample output 2
1
Explanation 2:
Array C constructed is 2 2 2 1 1 1 3 3
Second smallest element is 1, 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 inf 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;ll K;
cin>>N;
int c=0;
pair<int, ll> A[N];
for(int i=0;i<N;++i){
cin >> A[i].first ;
}
for(int i=0;i<N;++i){
cin >> A[i].second ;
}
cin>>K;
sort(A, A+N);
for(int i=0;i<N;++i){
K -= A[i].second;
if(K <= 0){
cout << A[i].first << endl;;
break;
}
}
#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: Alice has Q queries for you. If you can solve all her queries, she will invite you to participate in a fireworks display with her.
In each query, she gives you a positive integer N, and you have to find the number of positive integers M such that M × d(M) = N.
Here, d(M) refers to the sum of all digits of M. For example, d(1023) = 6.The first line consists of a single integer Q – the number of queries.
Then Q lines follow, each line containing a single integer N denoting a query.
<b> Constraints: </b>
1 ≤ Q ≤ 1000
1 ≤ N ≤ 10<sup>18</sup>Print Q lines, the i<sup>th</sup> line containing the answer to the i<sup>th</sup> query.Sample Input 1:
3
1
6
36
Sample Output 1:
1
0
2
Sample Explanation 1:
For the first query, the only possibility is 1.
For the third query, the only possibilities are 6 and 12., I have written this Solution Code: import java.io.*;
import java.util.*;
public class Main {
private static final int START_TEST_CASE = 1;
public static void solveCase(FastIO io, int testCase) {
final long N = io.nextLong();
int count = 0;
for (int i = 1; i <= 200; ++i) {
if (N % i == 0) {
long j = N / i;
if (digitSum(j) == i) {
++count;
}
}
}
io.println(count);
}
private static long digitSum(long x) {
long s = 0;
while (x > 0) {
s += x % 10;
x /= 10;
}
return s;
}
public static void solve(FastIO io) {
final int T = io.nextInt();
for (int t = 0; t < T; ++t) {
solveCase(io, START_TEST_CASE + t);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
private static class Solution implements Runnable {
@Override
public void run() {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
}
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(null, new Solution(), "Solution", 1 << 30);
t.start();
t.join();
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Alice has Q queries for you. If you can solve all her queries, she will invite you to participate in a fireworks display with her.
In each query, she gives you a positive integer N, and you have to find the number of positive integers M such that M × d(M) = N.
Here, d(M) refers to the sum of all digits of M. For example, d(1023) = 6.The first line consists of a single integer Q – the number of queries.
Then Q lines follow, each line containing a single integer N denoting a query.
<b> Constraints: </b>
1 ≤ Q ≤ 1000
1 ≤ N ≤ 10<sup>18</sup>Print Q lines, the i<sup>th</sup> line containing the answer to the i<sup>th</sup> query.Sample Input 1:
3
1
6
36
Sample Output 1:
1
0
2
Sample Explanation 1:
For the first query, the only possibility is 1.
For the third query, the only possibilities are 6 and 12., I have written this Solution Code:
q = int(input())
for _ in range(q):
n = int(input())
count = 0
for i in range(1,9*len(str(n))):
if not n % i:
dig = n//i
if sum(map(int,str(dig))) == i:
count += 1
print(count), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Alice has Q queries for you. If you can solve all her queries, she will invite you to participate in a fireworks display with her.
In each query, she gives you a positive integer N, and you have to find the number of positive integers M such that M × d(M) = N.
Here, d(M) refers to the sum of all digits of M. For example, d(1023) = 6.The first line consists of a single integer Q – the number of queries.
Then Q lines follow, each line containing a single integer N denoting a query.
<b> Constraints: </b>
1 ≤ Q ≤ 1000
1 ≤ N ≤ 10<sup>18</sup>Print Q lines, the i<sup>th</sup> line containing the answer to the i<sup>th</sup> query.Sample Input 1:
3
1
6
36
Sample Output 1:
1
0
2
Sample Explanation 1:
For the first query, the only possibility is 1.
For the third query, the only possibilities are 6 and 12., I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
#define int long long
// #pragma gcc optimize("ofast")
// #pragma gcc target("avx,avx2,fma")
#define all(x) (x).begin(), (x).end()
#define pb push_back
#define endl '\n'
#define fi first
#define se second
// const int mod = 1e9 + 7;
const int mod=998'244'353;
const long long INF = 2e18 + 10;
// const int INF=4e9+10;
#define readv(x, n) \
vector<int> x(n); \
for (auto &i : x) \
cin >> i;
template <typename t>
using v = vector<t>;
template <typename t>
using vv = vector<vector<t>>;
template <typename t>
using vvv = vector<vector<vector<t>>>;
typedef vector<int> vi;
typedef vector<double> vd;
typedef vector<vector<int>> vvi;
typedef vector<vector<vector<int>>> vvvi;
typedef vector<vector<vector<vector<int>>>> vvvvi;
typedef vector<vector<double>> vvd;
typedef pair<int, int> pii;
int multiply(int a, int b, int in_mod) { return (int)(1ll * a * b % in_mod); }
int mult_identity(int a) { return 1; }
const double pi = acosl(-1);
vector<vector<int> > multiply(vector<vector<int>> a, vector<vector<int>> b, int in_mod)
{
int n = a.size();
int l = b.size();
int m = b[0].size();
vector<vector<int> > result(n,vector<int>(n));
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
for(int k=0;k<l;k++)
{
result[i][j] = (result[i][j] + a[i][k]*b[k][j])%in_mod;
}
}
}
return result;
}
vector<vector<int>> operator%(vector<vector<int>> a, int in_mod)
{
for(auto &i:a)
for(auto &j:i)
j%=in_mod;
return a;
}
vector<vector<int>> mult_identity(vector<vector<int>> a)
{
int n=a.size();
vector<vector<int>> output(n, vector<int> (n));
for(int i=0;i<n;i++)
output[i][i]=1;
return output;
}
vector<int> mat_vector_product(vector<vector<int>> a, vector<int> b, int in_mod)
{
int n =a.size();
vector<int> output(n);
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
output[i]+=a[i][j]*b[j];
output[i]%=in_mod;
}
}
return output;
}
auto power(auto a, auto b, const int in_mod)
{
auto prod = mult_identity(a);
auto mult = a % in_mod;
while (b != 0)
{
if (b % 2)
{
prod = multiply(prod, mult, in_mod);
}
if(b/2)
mult = multiply(mult, mult, in_mod);
b /= 2;
}
return prod;
}
auto mod_inv(auto q, const int in_mod)
{
return power(q, in_mod - 2, in_mod);
}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define stp cout << fixed << setprecision(20);
int digit_sum(int x){
int sm = 0;
while(x){
sm += x%10;
x/= 10;
}
return sm;
}
void solv(){
int n;
cin>>n;
int cnt = 0;
for(int sm = 1;sm<= 200;sm++){
if(n %sm == 0){
if( digit_sum(n/sm) == sm){
cnt++;
}
}
}
cout<<cnt<<endl;
}
void solve()
{
int t = 1;
cin>>t;
for(int T=1;T<=t;T++)
{
// cout<<"Case #"<<T<<": ";
solv();
}
}
signed main()
{
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cerr.tie(NULL);
auto clk = clock();
// -------------------------------------Code starts here---------------------------------------------------------------------
signed t = 1;
// cin >> t;
for (signed test = 1; test <= t; test++)
{
// cout<<"Case #"<<test<<": ";
solve();
}
// -------------------------------------Code ends here------------------------------------------------------------------
clk = clock() - clk;
#ifndef ONLINE_JUDGE
cerr << fixed << setprecision(6) << "\nTime: " << ((float)clk) / CLOCKS_PER_SEC << "\n";
#endif
return 0;
}
/*
000100
1000100
1 0 -1 -2 -1 -2 -3
*/
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Ram is given an array A of N integers. He was asked to perform the following operation, The operation goes like this, Ram can choose at most X numbers of distinct elements from the array. Print the maximum sum he could achieve.The first line of the input contains an integer T denoting number of test cases.
For each test cases there will be two lines.
The first line will contain two space separated integers N and X.
The second line will contain the N space separated integers denoting array A.
<b>Constraints</b>
1 ≤ T ≤ 1000
1 ≤ X, N ≤ 10<sup>5</sup>
-10<sup>9</sup> ≤ A[i] ≤ 10<sup>9</sup>
Sum of N over all test cases will not exceed 2 x 10<sup>6</sup>For each test case print the maximum sum Ram can achieve.Sample Input
2
4 1
1 2 3 4
5 1
1 3 3 2 5
Sample Output
4
6
<b>Explanation:</b>
For the first test case, we can choose 4 and maximize the sum.
For the second test case, we can choose two 3 as we have chosen only 1 distinct integer and maximize the result., I have written this Solution Code: /**
* author: tourist1256
* created: 2022-07-12 13:59:06
**/
#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);
}
void solve() {
int n, k;
cin >> n >> k;
vector<int> a(n);
unordered_map<int, int> mp;
for (int i = 0; i < n; i++) {
cin >> a[i];
mp[a[i]] += a[i];
}
vector<int> v;
for (auto &it : mp) {
if (it.second > 0) {
v.push_back(it.second);
}
}
sort(v.begin(), v.end(), greater<int>());
debug(v);
int ans = 0;
for (int i = 0; i < min(k, (int)v.size()); i++) {
ans += v[i];
}
cout << ans << "\n";
}
int32_t main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
auto start = std::chrono::high_resolution_clock::now();
int tt;
cin >> tt;
while (tt--) {
solve();
}
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Ram is given an array A of N integers. He was asked to perform the following operation, The operation goes like this, Ram can choose at most X numbers of distinct elements from the array. Print the maximum sum he could achieve.The first line of the input contains an integer T denoting number of test cases.
For each test cases there will be two lines.
The first line will contain two space separated integers N and X.
The second line will contain the N space separated integers denoting array A.
<b>Constraints</b>
1 ≤ T ≤ 1000
1 ≤ X, N ≤ 10<sup>5</sup>
-10<sup>9</sup> ≤ A[i] ≤ 10<sup>9</sup>
Sum of N over all test cases will not exceed 2 x 10<sup>6</sup>For each test case print the maximum sum Ram can achieve.Sample Input
2
4 1
1 2 3 4
5 1
1 3 3 2 5
Sample Output
4
6
<b>Explanation:</b>
For the first test case, we can choose 4 and maximize the sum.
For the second test case, we can choose two 3 as we have chosen only 1 distinct integer and maximize the result., I have written this Solution Code: import java.util.*;
import java.io.*;
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]; // line length
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 br = new Reader();
long t = br.nextLong();
for (long i =0;i<t;i++){
long a=br.nextLong(),b=br.nextLong(),c=0;
long[] s = new long[(int) a];
for(long j=0;j<a;j++)
{
s[(int) j]=br.nextLong();
}
HashMap<Long,Integer> hash = new HashMap<Long,Integer>();
for(int k=0;k<s.length;k++){
if (hash.containsKey(s[k])) {
hash.put(s[k], hash.get(s[k]) + 1);
} else {
hash.put(s[k],1);
}
}
ArrayList<Long> arr = new ArrayList<Long>();
for (Map.Entry<Long, Integer> e : hash.entrySet()) {
arr.add(e.getKey()*e.getValue());
}
Collections.sort(arr);
Collections.reverse(arr);
for(long m:arr){
if(b>0 && m>=0){
c+=m;
b-=1;
}
}
System.out.println(c);
hash.clear();
arr.clear();
c=0;
}
}
}
, 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: 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 the first 2 terms A and B of an Arithmetic Series, tell the Nth term of the series.<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>NthAP()</b> that takes the integer A, B, and N as a parameter.
<b>Constraints:</b>
-10<sup>3</sup> ≤ A ≤ 10<sup>3</sup>
-10<sup>3</sup> ≤ B ≤ 10<sup>3</sup>
1 ≤ N ≤ 10<sup>4</sup>Return the Nth term of AP series.Sample Input 1:
2 3 4
Sample Output 1:
5
Sample Input 2:
1 2 10
Sample output 2:
10, I have written this Solution Code: class Solution {
public static int NthAP(int a, int b, int n){
return a+(n-1)*(b-a);
}
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: An array A of size N is called magical if:
1. Each element of the array is a positive integer not exceeding M, that is, 1 ≤ A<sub>i</sub> ≤ M for each i.
2. For each i such that 1 ≤ i ≤ N, define f(i) = A<sub>1</sub> | A<sub>2</sub> | ... A<sub>i</sub>, where x | y denotes the bitwise OR of x and y. Then, f(1) = f(2) = ... f(N) must hold.
Your task is to calculate the number of magical arrays of size N, modulo 998244353.The input consists of two space-separated integers N and M.
<b> Constraints: </b>
1 ≤ N ≤ 10<sup>5</sup>
1 ≤ M ≤ 10<sup>5</sup>Print a single integer – the number of magical arrays modulo 998244353.Sample Input 1:
2 3
Sample Output 1:
5
Sample Explanation:
The magical arrays are: [1, 1], [2, 2], [3, 3], [3, 1], [3, 2].
Sample Input 2:
1 50
Sample Output 2:
50
Sample Input 3:
707 707
Sample Output 3:
687062898, I have written this Solution Code: #include <bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
typedef long long ll;
typedef long double ld;
#define db(x) cerr << #x << ": " << x << '\n';
#define read(a) int a; cin >> a;
#define reads(s) string s; cin >> s;
#define readb(a, b) int a, b; cin >> a >> b;
#define readc(a, b, c) int a, b, c; cin >> a >> b >> c;
#define readarr(a, n) int a[(n) + 1] = {}; FOR(i, 1, (n)) {cin >> a[i];}
#define readmat(a, n, m) int a[n + 1][m + 1] = {}; FOR(i, 1, n) {FOR(j, 1, m) cin >> a[i][j];}
#define print(a) cout << a << endl;
#define printarr(a, n) FOR (i, 1, n) cout << a[i] << " "; cout << endl;
#define printv(v) for (int i: v) cout << i << " "; cout << endl;
#define printmat(a, n, m) FOR (i, 1, n) {FOR (j, 1, m) cout << a[i][j] << " "; cout << endl;}
#define all(v) v.begin(), v.end()
#define sz(v) (int)(v.size())
#define rz(v, n) v.resize((n) + 1);
#define pb push_back
#define fi first
#define se second
#define vi vector <int>
#define pi pair <int, int>
#define vpi vector <pi>
#define vvi vector <vi>
#define setprec cout << fixed << showpoint << setprecision(20);
#define FOR(i, a, b) for (int i = (a); i <= (b); i++)
#define FORD(i, a, b) for (int i = (a); i >= (b); i--)
const ll inf = 1e18;
const ll mod = 998244353;
const ll N = 2e5 + 1;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int power (int a, int b = mod - 2)
{
int res = 1;
while (b > 0) {
if (b & 1)
res = res * a % mod;
a = a * a % mod;
b >>= 1;
}
return res;
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
readb(n, m);
int ans = 0;
FOR (i, 1, m)
{
int x = (1 << (__builtin_popcountll(i))) - 1;
ans = (ans + power(x, n - 1)) % mod;
}
cout << ans;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Chinmay went to meet Bunty with 2x2 sweet because Bunty is a sweet child, and he saw Bunty playing with a right-angled isosceles triangle with base B. Chinmay came up with an intriguing notion and challenged Bunty to solve it; if he succeeds, he will be rewarded. Since Chinmay only purchased 'x' amount of sweets, he requests the greatest number of sweets that can fit in the triangle he's playing, with one side of the sweet parallel to the triangle's base.
Note: The base is the triangle's shortest side.The first line includes a space between "X" as the quantity of sweet Chinmay purchased and "B" as the base of the triangle.
<b>Constraints:</b>
1<b>≤</b> B <b>≤</b> 10<sup>4</sup>
1<b>≤</b> X <b>≤</b> 10<sup>9</sup>Output the maximum number of sweet he can able to fit in the triangle.Sample Input:
5 4
Sample Output:
1
Explanation:
In the triangle with base 4, Bunty can able to fit only one sweet in it., I have written this Solution Code: import java.util.*;
class Main{
public static void main(String []args){
Scanner scanner = new Scanner(System.in);
int x = scanner.nextInt();
int b = scanner.nextInt();
int n1 = (b / 2) - 1;
int a = (n1 * (n1 + 1)) / 2;
System.out.println((x >= a?a:x));
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Joffrey has issued orders for Stark's execution. Now, you are trying to predict if Stark will survive or not. You are confident that Stark's survival depends on the N<sup>th</sup> fibonacci number's parity. If it is odd you will predict that Stark lives but if it is even you will predict that Stark dies. Given N, print your prediction.
Fibonacci series is a series where,
Fibonacci(1) = 0
Fibonacci(2) = 1
Fibonacci(i) = Fibonacci(i-1) + Fibonacci(i-2); for i > 2Input Contains a single integer N.
Constraints:
1 <= N <= 1000000Print "Alive" if Nth Fibonacci number is odd and print "Dead" if Nth Fibonacci number is even.Sample Input 1
3
Sample Output 1
Alive
Explanation: Fibonacci(3) = 1 which is odd.
Sample Input 2
4
Sample Output 1
Dead
Explanation: Fibonacci(4) = 2 which is even., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws IOException{
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(is);
int n=Integer.parseInt(br.readLine().trim());
if(n%3==1)
System.out.println("Dead");
else
System.out.println("Alive");
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Joffrey has issued orders for Stark's execution. Now, you are trying to predict if Stark will survive or not. You are confident that Stark's survival depends on the N<sup>th</sup> fibonacci number's parity. If it is odd you will predict that Stark lives but if it is even you will predict that Stark dies. Given N, print your prediction.
Fibonacci series is a series where,
Fibonacci(1) = 0
Fibonacci(2) = 1
Fibonacci(i) = Fibonacci(i-1) + Fibonacci(i-2); for i > 2Input Contains a single integer N.
Constraints:
1 <= N <= 1000000Print "Alive" if Nth Fibonacci number is odd and print "Dead" if Nth Fibonacci number is even.Sample Input 1
3
Sample Output 1
Alive
Explanation: Fibonacci(3) = 1 which is odd.
Sample Input 2
4
Sample Output 1
Dead
Explanation: Fibonacci(4) = 2 which is even., I have written this Solution Code: n = int(input().strip())
if n%3 == 1:
print("Dead")
else:
print("Alive"), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Joffrey has issued orders for Stark's execution. Now, you are trying to predict if Stark will survive or not. You are confident that Stark's survival depends on the N<sup>th</sup> fibonacci number's parity. If it is odd you will predict that Stark lives but if it is even you will predict that Stark dies. Given N, print your prediction.
Fibonacci series is a series where,
Fibonacci(1) = 0
Fibonacci(2) = 1
Fibonacci(i) = Fibonacci(i-1) + Fibonacci(i-2); for i > 2Input Contains a single integer N.
Constraints:
1 <= N <= 1000000Print "Alive" if Nth Fibonacci number is odd and print "Dead" if Nth Fibonacci number is even.Sample Input 1
3
Sample Output 1
Alive
Explanation: Fibonacci(3) = 1 which is odd.
Sample Input 2
4
Sample Output 1
Dead
Explanation: Fibonacci(4) = 2 which is even., 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();
//////////////
typedef unsigned long long ull;
auto clk=clock();
#define all(x) x.begin(),x.end()
#define S second
#define F first
#define sz(x) ((long long)x.size())
#define int long long
#define f80 __float128
#define pii pair<int,int>
/////////////
signed main(){
#ifdef ANIKET_GOYAL
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
int n;
cin>>n;
if(n%3==1)
cout<<"Dead";
else
cout<<"Alive";
}, 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 ‘V’ kg of vibranium and Ultron wants his robot army to get the vibranium from that room. N robots are sent with the value of vibranium each of them has to bring. For each i the ith robot wants to bring ‘Ai’ amount of vibranium. Robots come in and try to take vibranium one by one in increasing order of their indices. Whenever a robot tries to take vibranium from the room, if the room has at least required amount of vibranium, then only the robot gets the vibranium otherwise the robot has to return without any vibranium. Each robot determine whether they will get the required amount of vibranium or not.The First line consists of two integers N( Number of robots ) and V ( Total amount of vibranium in the room ). The next line of input contains N space separated integers depicting the A1, A2. AN.
Constraints:-
1 <= N <= 100000
1 <= V <= 1000000
1 <= A[i] <= 100000Print N length string. The ith character should be 1 if the robot gets the vibranium or 0(zero) otherwise.Sample Input:-
5 10
3 5 3 2 1
Sample Output:-
11010
Explanation:-
The room initially contains 10kg of vibranium, the first robot comes and withdraws 3kg, the the vibranium left in the room is 7kg, then the second robot comes and withdraws 5kg, amount left is 2kg ; when the 3rd robot comes to take 3kg of vibranium he returns empty handed because the amount of vibranium left is only 2kg. The 4th robot comes and takes 2kg of vibranium and the 5th robot returns empty handed as there is no vibranium left to take from the room.
Sample Input:-
5 1
2 3 4 5 6
Sample Output:-
00000, 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);
int n = sc.nextInt();
int total = sc.nextInt();
int[] a = new int[n];
for(int i = 0; i < n; i++){
a[i] = sc.nextInt();
}
StringBuilder sb = new StringBuilder();
for(int i = 0 ; i < n ; i++){
if(total >= a[i]){
sb.append('1');
total-=a[i];
}else{
sb.append('0');
}
}
System.out.println(sb);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: There is a room filled with ‘V’ kg of vibranium and Ultron wants his robot army to get the vibranium from that room. N robots are sent with the value of vibranium each of them has to bring. For each i the ith robot wants to bring ‘Ai’ amount of vibranium. Robots come in and try to take vibranium one by one in increasing order of their indices. Whenever a robot tries to take vibranium from the room, if the room has at least required amount of vibranium, then only the robot gets the vibranium otherwise the robot has to return without any vibranium. Each robot determine whether they will get the required amount of vibranium or not.The First line consists of two integers N( Number of robots ) and V ( Total amount of vibranium in the room ). The next line of input contains N space separated integers depicting the A1, A2. AN.
Constraints:-
1 <= N <= 100000
1 <= V <= 1000000
1 <= A[i] <= 100000Print N length string. The ith character should be 1 if the robot gets the vibranium or 0(zero) otherwise.Sample Input:-
5 10
3 5 3 2 1
Sample Output:-
11010
Explanation:-
The room initially contains 10kg of vibranium, the first robot comes and withdraws 3kg, the the vibranium left in the room is 7kg, then the second robot comes and withdraws 5kg, amount left is 2kg ; when the 3rd robot comes to take 3kg of vibranium he returns empty handed because the amount of vibranium left is only 2kg. The 4th robot comes and takes 2kg of vibranium and the 5th robot returns empty handed as there is no vibranium left to take from the room.
Sample Input:-
5 1
2 3 4 5 6
Sample Output:-
00000, I have written this Solution Code: N,V=list(map(int,input().split()))
lis=list(map(int,input().split()))
rstr=''
for i in lis:
if V>=i:
V=V-i
rstr+='1'
else:
rstr+='0'
print(rstr), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: There is a room filled with ‘V’ kg of vibranium and Ultron wants his robot army to get the vibranium from that room. N robots are sent with the value of vibranium each of them has to bring. For each i the ith robot wants to bring ‘Ai’ amount of vibranium. Robots come in and try to take vibranium one by one in increasing order of their indices. Whenever a robot tries to take vibranium from the room, if the room has at least required amount of vibranium, then only the robot gets the vibranium otherwise the robot has to return without any vibranium. Each robot determine whether they will get the required amount of vibranium or not.The First line consists of two integers N( Number of robots ) and V ( Total amount of vibranium in the room ). The next line of input contains N space separated integers depicting the A1, A2. AN.
Constraints:-
1 <= N <= 100000
1 <= V <= 1000000
1 <= A[i] <= 100000Print N length string. The ith character should be 1 if the robot gets the vibranium or 0(zero) otherwise.Sample Input:-
5 10
3 5 3 2 1
Sample Output:-
11010
Explanation:-
The room initially contains 10kg of vibranium, the first robot comes and withdraws 3kg, the the vibranium left in the room is 7kg, then the second robot comes and withdraws 5kg, amount left is 2kg ; when the 3rd robot comes to take 3kg of vibranium he returns empty handed because the amount of vibranium left is only 2kg. The 4th robot comes and takes 2kg of vibranium and the 5th robot returns empty handed as there is no vibranium left to take from the room.
Sample Input:-
5 1
2 3 4 5 6
Sample Output:-
00000, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
#define int long long
signed main() {
int n,k;
cin>>n>>k;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
vector<int> v;
for(int i=0;i<n;i++){
if(arr[i]<=k){
k=k-arr[i];
v.push_back(1);
}
else{
v.push_back(0);
}
}
for(int i=0;i<n;i++){
cout<<v[i];
}
cout<<endl;
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: We define a weird series as follows:
7, 77, 777, 7777, 77777, 777777,. .
Given a positive integer N find where is first occurrence of a number divisible by N in the given series.
If the series contains no multiple of N, print -1 instead.Input contains a single integer N.
Constraints:
1 <= N <= 1000000Print the position of the first position of a multiple of N in the series. (For example, if the first occurrence is the third element of the series, print 3)Sample Input 1
101
Sample Output 1
4
Explanation: 7, 77, 777 are not multiple of 101 whereas 7777 is a multiple of 101.
Sample Input 2
2
Sample Output 2
-1
Sample Input 3
7
Sample Output 3
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 num = Integer.parseInt(br.readLine());
System.out.print(wierdSeven(num));
}
private static int wierdSeven(int n){
int temp = 7,multiple=0;
for(int i=1;i<=n;i++){
multiple = multiple+temp;
if(multiple%n==0){
return i;
}
multiple = multiple%n;
temp = temp*10;
temp = temp%n;
}
return -1;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: We define a weird series as follows:
7, 77, 777, 7777, 77777, 777777,. .
Given a positive integer N find where is first occurrence of a number divisible by N in the given series.
If the series contains no multiple of N, print -1 instead.Input contains a single integer N.
Constraints:
1 <= N <= 1000000Print the position of the first position of a multiple of N in the series. (For example, if the first occurrence is the third element of the series, print 3)Sample Input 1
101
Sample Output 1
4
Explanation: 7, 77, 777 are not multiple of 101 whereas 7777 is a multiple of 101.
Sample Input 2
2
Sample Output 2
-1
Sample Input 3
7
Sample Output 3
1, I have written this Solution Code: a = int(input())
lst = 0
ans = 1
if(a%2!=0 and a%5!=0 and a%17!=0):
lst = 7%a
while(lst!=0):
ans = ans+1
lst*=10
lst=lst+7
lst%=a
print(ans)
else:
print("-1", end=""), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: We define a weird series as follows:
7, 77, 777, 7777, 77777, 777777,. .
Given a positive integer N find where is first occurrence of a number divisible by N in the given series.
If the series contains no multiple of N, print -1 instead.Input contains a single integer N.
Constraints:
1 <= N <= 1000000Print the position of the first position of a multiple of N in the series. (For example, if the first occurrence is the third element of the series, print 3)Sample Input 1
101
Sample Output 1
4
Explanation: 7, 77, 777 are not multiple of 101 whereas 7777 is a multiple of 101.
Sample Input 2
2
Sample Output 2
-1
Sample Input 3
7
Sample Output 3
1, 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 i, j;
long long law;
long long seven_multi = 0;
long long temp_pow = 7;
cin >> law;
for (i = 1, temp_pow = 7; i <= law; i++) {
seven_multi += temp_pow;
if ((seven_multi %= law) == 0) {
cout << i << endl;
return 0;
}
temp_pow *= 10;
temp_pow %= law;
}
cout << -1 << endl;
return 0;
#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: Given a binary tree containing with N nodes and an integer X. Your task is to complete the function countSubtreesWithSumX() that returns the count of the number of subtress having total node’s data sum equal to a value X.
Example: A tree given below<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>countSubtreesWithSumX()</b> that takes "root" node and the integer x as parameter.
<b>Constraints:</b>
1 <= T <= 100
1 <= N <= 10^3
1 <= node values <= 10^4
<b>Sum of "N" over all testcases does not exceed 10^5</b>Return the number of subtrees with sum X. The driver code will take care of printing it.Sample Input:
1
3 5
1 2 3
Sum=5
Tree:-
1
/ \
2 3
Sample Output:
0
Explanation:
No subtree has a sum equal to 5.
Sample Input:-
1
5 5
2 1 3 4 5
Sum=5
Tree:-
2
/ \
1 3
/ \
4 5
Sample Output:-
1, I have written this Solution Code: static int c = 0;
static int countSubtreesWithSumXUtil(Node root,int x)
{
// if tree is empty
if (root==null)return 0;
// sum of nodes in the left subtree
int ls = countSubtreesWithSumXUtil(root.left,x);
// sum of nodes in the right subtree
int rs = countSubtreesWithSumXUtil(root.right, x);
int sum = ls + rs + root.data;
// if tree's nodes sum == x
if (sum == x)c++;
return sum;
}
static int countSubtreesWithSumX(Node root, int x)
{
c = 0;
// if tree is empty
if (root==null)return 0;
// sum of nodes in the left subtree
int ls = countSubtreesWithSumXUtil(root.left, x);
// sum of nodes in the right subtree
int rs = countSubtreesWithSumXUtil(root.right, x);
// check if above sum is equal to x
if ((ls + rs + root.data) == x)c++;
return c;
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Let's define P[i] as the ith Prime Number. Therefore, P[1]=2, P[2]=3, P[3]=5, so on.
Given two integers L, R (L<=R), find the value of P[L]+P[L+1]+P[L+2]...+P[R].The first line of the input contains an integer T denoting the number of test cases.
The next T lines contain two integers L and R.
Constraints
1 <= T <= 50000
1 <= L <= R <= 50000For each test case, print one line corresponding to the required valueSample Input
4
1 3
2 4
5 5
1 5
Sample Output
10
15
11
28, 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());
int max = 1000001;
boolean isNotPrime[] = new boolean[max];
ArrayList<Integer> arr = new ArrayList<Integer>();
isNotPrime[0] = true; isNotPrime[1] = true;
for (int i=2; i*i <max; i++) {
if (!isNotPrime[i]) {
for (int j=i*i; j<max; j+= i) {
isNotPrime[j] = true;
}
}
}
for(int i=2; i<max; i++) {
if(!isNotPrime[i]) {
arr.add(i);
}
}
while(t-- > 0) {
String str[] = br.readLine().trim().split(" ");
int l = Integer.parseInt(str[0]);
int r = Integer.parseInt(str[1]);
System.out.println(primeRangeSum(l,r,arr));
}
}
static long primeRangeSum(int l , int r, ArrayList<Integer> arr) {
long sum = 0;
for(int i=l; i<=r;i++) {
sum += arr.get(i-1);
}
return sum;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Let's define P[i] as the ith Prime Number. Therefore, P[1]=2, P[2]=3, P[3]=5, so on.
Given two integers L, R (L<=R), find the value of P[L]+P[L+1]+P[L+2]...+P[R].The first line of the input contains an integer T denoting the number of test cases.
The next T lines contain two integers L and R.
Constraints
1 <= T <= 50000
1 <= L <= R <= 50000For each test case, print one line corresponding to the required valueSample Input
4
1 3
2 4
5 5
1 5
Sample Output
10
15
11
28, I have written this Solution Code: def SieveOfEratosthenes(n):
prime = [True for i in range(n+1)]
pri = []
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
for p in range(2, n+1):
if prime[p]:
pri.append(p)
return pri
N = int(input())
X = []
prim = SieveOfEratosthenes(1000000)
for i in range(1,len(prim)):
prim[i] = prim[i]+prim[i-1]
for i in range(N):
nnn = input()
X.append((int(nnn.split()[0]),int(nnn.split()[1])))
for xx,yy in X:
if xx==1:
print(prim[yy-1])
else:
print(prim[yy-1]-prim[xx-2])
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Let's define P[i] as the ith Prime Number. Therefore, P[1]=2, P[2]=3, P[3]=5, so on.
Given two integers L, R (L<=R), find the value of P[L]+P[L+1]+P[L+2]...+P[R].The first line of the input contains an integer T denoting the number of test cases.
The next T lines contain two integers L and R.
Constraints
1 <= T <= 50000
1 <= L <= R <= 50000For each test case, print one line corresponding to the required valueSample Input
4
1 3
2 4
5 5
1 5
Sample Output
10
15
11
28, 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 = 1e6 + 5;
const int mod = 1e9 + 7;
const int inf = 1e9 + 9;
int a[N];
signed main() {
IOS;
vector<int> v;
v.push_back(0);
for(int i = 2; i < N; i++){
if(a[i]) continue;
v.push_back(i);
for(int j = i*i; j < N; j += i)
a[j] = 1;
}
int p = 0;
for(auto &i: v){
i += p;
p = i;
}
int t; cin >> t;
while(t--){
int l, r;
cin >> l >> r;
cout << v[r] - v[l-1] << endl;
}
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Write a class with the name SumCalculator. The class needs two fields (public variables) with names num1 and num2 both of type int.
Write the following methods (instance methods):
<b>*Method named sum without any parameters, it needs to return the value of num1 + num2.</b>
<b>*Method named sum2 with two parameters a, b, it needs to return the value of a + b.</b>
<b>*Method named fromObject with two parameters of type sumCalculator object named obj1 and obj2, and you have to call sum function for respective object and return sum of both</b>
NOTE: All methods should be defined as public, NOT public static.
NOTE: In total, you have to write 3 methods.
NOTE: Do not add the main method to the solution code.You don't have to take any input, You only have to write class <b>SumCalculator</b>.Output will be printed by tester, "Correct" if your code is perfectly fine otherwise "Wrong".Sample Input:
1
Sample Output:
Correct, I have written this Solution Code: class SumCalculator():
def __init__(self,a,b):
self.a=a
self.b=b
def sum(self):
return self.a+self.b
def sum2(self,a,b):
return a+b
def fromObject(self,ob1,ob2):
return ob1.sum+ob2.sum, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Write a class with the name SumCalculator. The class needs two fields (public variables) with names num1 and num2 both of type int.
Write the following methods (instance methods):
<b>*Method named sum without any parameters, it needs to return the value of num1 + num2.</b>
<b>*Method named sum2 with two parameters a, b, it needs to return the value of a + b.</b>
<b>*Method named fromObject with two parameters of type sumCalculator object named obj1 and obj2, and you have to call sum function for respective object and return sum of both</b>
NOTE: All methods should be defined as public, NOT public static.
NOTE: In total, you have to write 3 methods.
NOTE: Do not add the main method to the solution code.You don't have to take any input, You only have to write class <b>SumCalculator</b>.Output will be printed by tester, "Correct" if your code is perfectly fine otherwise "Wrong".Sample Input:
1
Sample Output:
Correct, I have written this Solution Code: class SumCalculator{
public int num1,num2;
SumCalculator(int _num1,int _num2){
num1=_num1;
num2=_num2;
}
public int sum() {
return num1+num2;
}
public int sum2(int a,int b){
return a+b;
}
public int fromObject(SumCalculator obj1,SumCalculator obj2){
return obj1.sum() + obj2.sum();
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer N, find the number of integers from 1 to N, that are odd as well as have odd number of digits, eg: 333 will be counted while 33 or 332 will not be counted.The first line and the only line of the input contains an integer N.
Constraints
1 <= N <= 100000Output a single integer, the number of integers that are odd as well as have odd number of digits in their decimal representation.Sample Input
13
Sample Output
5
Explanation: Only 1, 3, 5, 7, and 9 meet the criteria.
Sample Input
101
Sample Output
6, I have written this Solution Code: a=int(input())
p=0
for i in range((a)+1):
if (i)%2!=0 and len(str(i))%2!=0:
p+=1
print(p), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer N, find the number of integers from 1 to N, that are odd as well as have odd number of digits, eg: 333 will be counted while 33 or 332 will not be counted.The first line and the only line of the input contains an integer N.
Constraints
1 <= N <= 100000Output a single integer, the number of integers that are odd as well as have odd number of digits in their decimal representation.Sample Input
13
Sample Output
5
Explanation: Only 1, 3, 5, 7, and 9 meet the criteria.
Sample Input
101
Sample Output
6, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
#define sd(x) scanf("%d", &x)
#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;
#define MOD 1000000007
#define INF 1000000000000000007
#define MAXN 300005
// it's swapnil07 ;)
int ctd(int i){
int ct = 0;
while(i){
i/=10;
ct++;
}
return ct;
}
signed main(){
fast
#ifdef SWAPNIL07
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n; cin>>n;
int ans = 0;
For(i, 1, n+1){
int x = ctd(i);
if(x%2 && i%2)
ans++;
}
cout<<ans;
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer N, find the number of integers from 1 to N, that are odd as well as have odd number of digits, eg: 333 will be counted while 33 or 332 will not be counted.The first line and the only line of the input contains an integer N.
Constraints
1 <= N <= 100000Output a single integer, the number of integers that are odd as well as have odd number of digits in their decimal representation.Sample Input
13
Sample Output
5
Explanation: Only 1, 3, 5, 7, and 9 meet the criteria.
Sample Input
101
Sample Output
6, I have written this Solution Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int cnt=0;
for(int i=1;i<=n;i++){
if(check(i)==1){
cnt++;
}
}
System.out.println(cnt);
}
static int check(int i){
if(i%2==0){return 0;}
int cnt=0;
while(i>0){
i/=10;
cnt++;
}
return cnt%2;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a Deque and Q queries. The task is to perform some operation on Deque according to the queries as described in input:
Note:-if deque is empty than pop operation will do nothing, and -1 will be printed as a front and rear element of queue if it is empty.User task:
Since this will be a functional problem, you don't have to take input. You just have to complete the functions:
<b>push_front_pf()</b>:- that takes the deque and the integer to be added as a parameter.
<b>push_bac_pb()</b>:- that takes the deque and the integer to be added as a parameter.
<b>pop_back_ppb()</b>:- that takes the deque as parameter.
<b>front_dq()</b>:- that takes the deque as parameter.
Constraints:
1 <= N(Number of queries) <= 10<sup>3</sup>
<b>Custom Input: </b>
First line of input should contain the number of queries Q. Next, Q lines should contain any of the given operations:-
For <b>push_front</b> use <b> pf x</b> where x is the element to be added
For <b>push_rear</b> use <b> pb x</b> where x is the element to be added
For <b>pop_back</b> use <b> pp_b</b>
For <b>Display Front</b> use <b>f</b>
Moreover driver code will print
Front element of deque in each push_front opertion
Last element of deque in each push_back operation
Size of deque in each pop_back operation The front_dq() function will return the element at front of your deque in a new line, if the deque is empty you just need to return -1 in the function.Sample Input:
6
push_front 2
push_front 3
push_rear 5
display_front
pop_rear
display_front
Sample Output:
3
3, I have written this Solution Code:
static void push_back_pb(Deque<Integer> dq, int x)
{
dq.add(x);
}
static void push_front_pf(Deque<Integer> dq, int x)
{
dq.addFirst(x);
}
static void pop_back_ppb(Deque<Integer> dq)
{
if(!dq.isEmpty())
dq.pollLast();
else return;
}
static int front_dq(Deque<Integer> dq)
{
if(!dq.isEmpty())
return dq.peek();
else return -1;
}
, 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: 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: 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: Given an array of N integers containing only 0 or 1. You can do the following operations on the array:
<ul><li>swap elements at two indices</li><li>choose one index and change its value from 0 to 1 or vice-versa.</li></ul>
You have to do the minimum number of the above operations such that the final array is non-decreasing.
<b>Note</b> Consider 1 based Array-indexingThe first line of input contains a single integer N.
The second line of input contains N space-separated integers denoting the array.
Constraints:
1 ≤ N ≤ 100000
elements of the array are 0 or 1.Minimum number of moves required such that the final array is non- decreasing.Sample Input 1
5
1 1 0 0 1
Sample Output 1
2
Explanation:
Swap indices (1, 3)
Swap indices (2, 4)
Sample Input 2
5
0 0 1 1 1
Sample Output 2
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));
int n = Integer.parseInt(br.readLine().trim());
String array[] = br.readLine().trim().split(" ");
boolean decreasingOrder = false;
int[] arr = new int[n];
int totalZeroCount = 0,
totalOneCount = 0;
for(int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(array[i]);
if(i != 0 && arr[i] < arr[i - 1])
decreasingOrder = true;
if(arr[i] % 2 == 0)
++totalZeroCount;
else
++totalOneCount;
}
if(!decreasingOrder) {
System.out.println("0");
} else {
int oneCount = 0;
for(int i = 0; i < totalZeroCount; i++) {
if(arr[i] == 1)
++oneCount;
}
System.out.println(oneCount);
}
}
}, 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 containing only 0 or 1. You can do the following operations on the array:
<ul><li>swap elements at two indices</li><li>choose one index and change its value from 0 to 1 or vice-versa.</li></ul>
You have to do the minimum number of the above operations such that the final array is non-decreasing.
<b>Note</b> Consider 1 based Array-indexingThe first line of input contains a single integer N.
The second line of input contains N space-separated integers denoting the array.
Constraints:
1 ≤ N ≤ 100000
elements of the array are 0 or 1.Minimum number of moves required such that the final array is non- decreasing.Sample Input 1
5
1 1 0 0 1
Sample Output 1
2
Explanation:
Swap indices (1, 3)
Swap indices (2, 4)
Sample Input 2
5
0 0 1 1 1
Sample Output 2
0, 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];
}
int cnt = 0;
for (int i = 0; i < n; i++) {
if (a[i]==0) cnt++;
}
int ans = 0;
for (int i = 0; i < cnt; i++) if (a[i] == 1) ans++;
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: Given an array of N integers containing only 0 or 1. You can do the following operations on the array:
<ul><li>swap elements at two indices</li><li>choose one index and change its value from 0 to 1 or vice-versa.</li></ul>
You have to do the minimum number of the above operations such that the final array is non-decreasing.
<b>Note</b> Consider 1 based Array-indexingThe first line of input contains a single integer N.
The second line of input contains N space-separated integers denoting the array.
Constraints:
1 ≤ N ≤ 100000
elements of the array are 0 or 1.Minimum number of moves required such that the final array is non- decreasing.Sample Input 1
5
1 1 0 0 1
Sample Output 1
2
Explanation:
Swap indices (1, 3)
Swap indices (2, 4)
Sample Input 2
5
0 0 1 1 1
Sample Output 2
0, I have written this Solution Code: n=int(input())
l=list(map(int,input().split()))
x=l.count(0)
c=0
for i in range(0,x):
if(l[i]==1):
c+=1
print(c), In this Programming Language: Python, 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: While Solo was enjoying her daddy's party, her little sister Tono gave her the following problem to solve:
Given an array A of N integers, find the number of occurrences of the maximum integer in the array.
As Solo is small and enjoying the party, please help her solve this problem.The first line of the input contains an integer N, the size of the array A.
The next line contains N space separated integers, the elements of the array A.
Constraints
1 <= N <= 100
1 <= A[i] <= 100Output a single integer, the number of occurrences of the maximum integer in the array A.Sample Input
5
1 2 3 2 1
Sample Output
1
Explanation: The maximum integer is 3 and it occurs once in the array.
Sample Input
5
5 5 5 5 5
Sample Output
5, 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());
int[] arr=new int[n];
String[] s=br.readLine().trim().split(" ");
for(int i=0;i<arr.length;i++)
arr[i]=Integer.parseInt(s[i]);
int max=Integer.MIN_VALUE,c=0;
for(int i=0;i<arr.length;i++){
if(max==arr[i])
c++;
if(max<arr[i]){
max=arr[i];
c=1;
}
}
System.out.println(c);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: While Solo was enjoying her daddy's party, her little sister Tono gave her the following problem to solve:
Given an array A of N integers, find the number of occurrences of the maximum integer in the array.
As Solo is small and enjoying the party, please help her solve this problem.The first line of the input contains an integer N, the size of the array A.
The next line contains N space separated integers, the elements of the array A.
Constraints
1 <= N <= 100
1 <= A[i] <= 100Output a single integer, the number of occurrences of the maximum integer in the array A.Sample Input
5
1 2 3 2 1
Sample Output
1
Explanation: The maximum integer is 3 and it occurs once in the array.
Sample Input
5
5 5 5 5 5
Sample Output
5, I have written this Solution Code: n=int(input())
a=list(map(int,input().split()))
print(a.count(max(a))), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: While Solo was enjoying her daddy's party, her little sister Tono gave her the following problem to solve:
Given an array A of N integers, find the number of occurrences of the maximum integer in the array.
As Solo is small and enjoying the party, please help her solve this problem.The first line of the input contains an integer N, the size of the array A.
The next line contains N space separated integers, the elements of the array A.
Constraints
1 <= N <= 100
1 <= A[i] <= 100Output a single integer, the number of occurrences of the maximum integer in the array A.Sample Input
5
1 2 3 2 1
Sample Output
1
Explanation: The maximum integer is 3 and it occurs once in the array.
Sample Input
5
5 5 5 5 5
Sample Output
5, 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(101, 0);
For(i, 0, n){
int x; cin>>x;
a[x]++;
}
for(int i=100; i>=1; i--){
if(a[i]){
cout<<a[i];
return;
}
}
}
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 a sorted doubly linked list containing n nodes. Your task is to remove duplicate nodes from the given list.
Example 1:
Input
1<->2<->2-<->3<->3<->4
Output:
1<->2<->3<->4
Example 2:
Input
1<->1<->1<->1
Output
1<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>deleteDuplicates()</b> that takes head node as parameter.
Constraints:
1 <=N <= 10000
1 <= Node. data<= 2*10000Return the head of the modified list.Sample Input:-
6
1 2 2 3 3 4
Sample Output:-
1 2 3 4
Sample Input:-
4
1 1 1 1
Sample Output:-
1, I have written this Solution Code: public static Node deleteDuplicates(Node head)
{
/* if list is empty */
if (head== null)
return head;
Node current = head;
while (current.next != null)
{
/* Compare current node with next node */
if (current.val == current.next.val)
/* delete the node pointed to by
' current->next' */
deleteNode(head, current.next);
/* else simply move to the next node */
else
current = current.next;
}
return head;
}
/* Function to delete a node in a Doubly Linked List.
head_ref --> pointer to head node pointer.
del --> pointer to node to be deleted. */
public static void deleteNode(Node head, Node del)
{
/* base case */
if(head==null || del==null)
{
return ;
}
/* If node to be deleted is head node */
if(head==del)
{
head=del.next;
}
/* Change next only if node to be deleted
is NOT the last node */
if(del.next!=null)
{
del.next.prev=del.prev;
}
/* Change prev only if node to be deleted
is NOT the first node */
if (del.prev != null)
del.prev.next = del.next;
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a number, you task is to reverse its digits. If the reversed number contains 0s in the beginning, you must remove them as well.First line consists of a single integer denoting n.
Constraint:-
1<=size of n<=100Output is a single line containing reversed number n.Sample Input
123445
Sample Output
544321
Sample Input
16724368
Sample Output
86342761, 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();
int i=str.length()-1;
if(i==0){
int number=Integer.parseInt(str);
System.out.println(number);
}else{
while(str.charAt(i)=='0'){
i--;
}
for(int j=i;j>=0;j--){
System.out.print(str.charAt(j));
}
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a number, you task is to reverse its digits. If the reversed number contains 0s in the beginning, you must remove them as well.First line consists of a single integer denoting n.
Constraint:-
1<=size of n<=100Output is a single line containing reversed number n.Sample Input
123445
Sample Output
544321
Sample Input
16724368
Sample Output
86342761, I have written this Solution Code: n=int(input())
def reverse(n):
return int(str(n)[::-1])
print(reverse(n)), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a number, you task is to reverse its digits. If the reversed number contains 0s in the beginning, you must remove them as well.First line consists of a single integer denoting n.
Constraint:-
1<=size of n<=100Output is a single line containing reversed number n.Sample Input
123445
Sample Output
544321
Sample Input
16724368
Sample Output
86342761, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
cin>>s;
reverse(s.begin(),s.end());
int I;
for( I=0;I<s.length();I++){
if(s[I]!='0'){break;}
}
if(I==s.length()){cout<<0;return 0;}
for(int j=I;j<s.length();j++){
cout<<s[j];}
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Is it possible to sort a given string s with at most a single deletion operation allowed, i.e., removing any one character from the string?The first line contains string s.
<b>Constraints</b>
n = |s|
1 ≤ n ≤ 100Print "YES" without quotes, if it is possible to sort the string, otherwise print "NO".Sample Input 1:
abcac
Sample Output:
YES
Explanation:
we can delete 'a' at index 4., I have written this Solution Code: import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.*;
public class Main {
public static String sortStringWithSingleDeletion(String s) {
int n = s.length();
for (int i = 0; i < n; i++) {
StringBuilder sb = new StringBuilder();
sb.append(s.substring(0, i)).append(s.substring(i + 1));
boolean vd=true;
for(int j=1;j<n-1;j++){
if(sb.charAt(j)<sb.charAt(j-1)){
vd=false;
break;
}
}
if(vd){
return "YES";
}
}
return "NO";
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
int n=s.length();
assert n>=1&&n<=100 : "Input not valid";
System.out.print(sortStringWithSingleDeletion(s));
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a string S. Two position i and j of the string are friends if they have the same character. The distance between two friends at positions i and j is defined as |i- j|. Find the sum of distances of all the pairs of friends in the given strings.First line of input contains a single string S.
Constraints:
1 <= |S| <= 1000000
String contains lowercase english letters.Output a single integer which is the sum of distance of all the pair of friends in the given strings.Sample Input
ababa
Sample Output
10
Explanation: Friend pairs - (1, 3) (1, 5) (2, 4) (3, 5), I have written this Solution Code: import java.io.*;
import java.io.IOException;
import java.util.*;
class Main {
public static long mod = (long)Math.pow(10,9)+7 ;
public static double epsilon=0.00000000008854;
public static InputReader sc = new InputReader(System.in);
public static PrintWriter pw = new PrintWriter(System.out);
public static void main(String[] args) {
String s=sc.nextLine();
int n=s.length();
int hnum[]=new int[26];
int hpast[]=new int[26];
Arrays.fill(hpast,-1);
long hsum[]=new long[26];
long ans=0;
for(int i=0;i<n;i++){
int k=s.charAt(i)-'a';
if(hpast[k]!=-1)
hsum[k]=hsum[k]+(i-hpast[k])*hnum[k];
ans+=hsum[k];
hnum[k]++;
hpast[k]=i;
}
pw.println(ans);
pw.flush();
pw.close();
}
public static Comparator<Long[]> column(int i){
return
new Comparator<Long[]>() {
@Override
public int compare(Long[] o1, Long[] o2) {
return o1[i].compareTo(o2[i]);
}
};
}
public static Comparator<Integer[]> col(int i){
return
new Comparator<Integer[]>() {
@Override
public int compare(Integer[] o1, Integer[] o2) {
return o1[i].compareTo(o2[i]);
}
};
}
public static String reverseString(String s){
StringBuilder input1 = new StringBuilder();
input1.append(s);
input1 = input1.reverse();
return input1.toString();
}
public static int[] scanArray(int n){
int a[]=new int [n];
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
return a;
}
public static long[] scanLongArray(int n){
long a[]=new long [n];
for(int i=0;i<n;i++)
a[i]=sc.nextLong();
return a;
}
public static String [] scanStrings(int n){
String a[]=new String [n];
for(int i=0;i<n;i++)
a[i]=sc.nextLine();
return a;
}
public static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a string S. Two position i and j of the string are friends if they have the same character. The distance between two friends at positions i and j is defined as |i- j|. Find the sum of distances of all the pairs of friends in the given strings.First line of input contains a single string S.
Constraints:
1 <= |S| <= 1000000
String contains lowercase english letters.Output a single integer which is the sum of distance of all the pair of friends in the given strings.Sample Input
ababa
Sample Output
10
Explanation: Friend pairs - (1, 3) (1, 5) (2, 4) (3, 5), I have written this Solution Code: def findS(s):
visited= [ 0 for i in range(256)];
distance =[0 for i in range (256)];
for i in range(256):
visited[i]=0;
distance[i]=0;
sum=0;
for i in range(len(s)):
sum+=visited[ord(s[i])] * i - distance[ord(s[i])];
visited[ord(s[i])] +=1;
distance[ord(s[i])] +=i;
return sum;
if __name__ == '__main__':
s=input("");
print(findS(s));, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a string S. Two position i and j of the string are friends if they have the same character. The distance between two friends at positions i and j is defined as |i- j|. Find the sum of distances of all the pairs of friends in the given strings.First line of input contains a single string S.
Constraints:
1 <= |S| <= 1000000
String contains lowercase english letters.Output a single integer which is the sum of distance of all the pair of friends in the given strings.Sample Input
ababa
Sample Output
10
Explanation: Friend pairs - (1, 3) (1, 5) (2, 4) (3, 5), I have written this Solution Code: #pragma GCC optimize ("O3")
#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
string s;
cin>>s;
int c[26]={};
int f[26]={};
int ans=0;
int n=s.length();
for(int i=0;i<n;++i){
ans+=f[s[i]-'a']*i-c[s[i]-'a'];
f[s[i]-'a']++;
c[s[i]-'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: Padding is a process of adding layers of zeros to the input image. If we want to have p layers of padding then we have to add p layers of zeroes on borders.
Given two integers N and p. How many zeroes are needed to be added to N X N image to give p layers of zero padding?First line contains N and p.
<b>Constraints</b>
1 ≤ N, p ≤ 10<sup>8</sup>Output a single integer denoting the required number of zeroes.Input:
3 1
Output:
16
Explanation :
0 0 0 0 0
0 1 2 3 0
0 4 5 6 0
0 7 8 9 0
0 0 0 0 0, I have written this Solution Code: import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
long n=Long.parseLong(in.next());
long p=Long.parseLong(in.next());
long ans=(n+2*p) * (n+2*p) - (n*n);
out.print(ans);
out.close();
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given a string S (containing only lowercase characters). You need to print the repeated character whose first appearance is leftmost.The first line of input contains T denoting the number of testcases. T testcases follow.
Each testcase contains one line of input containing the string S.
Constraints:
1 <= T <= 100
1 <= |S| <= 1000For each testcase, in a new line, print the character. If not found then print "-1".Input:
2
geeksforgeeks
abcd
Output:
g
-1
Explanation:
Testcase1: We see that both e and g repeat as we move from left to right. But the leftmost is g so we print g.
Testcase2: No character repeats so we print -1.
, I have written this Solution Code:
function leftMostOcurringChar(str) {
// write code here
// do not console.log answer
// return the answer using return keyword
let firstIndex = new Array(256).fill(-1);
let res = Number.MAX_VALUE;
for (let i = 0; i < str.length; i++)
{
if (firstIndex[str[i].charCodeAt()] == -1)
{
firstIndex[str[i].charCodeAt()] = i;
}
else
{
res = Math.min(res, firstIndex[str[i].charCodeAt()]);
}
}
const ans = (res == Number.MAX_VALUE) ? -1 : res;
if (ans === -1) return -1;
return str[ans]
}, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given a string S (containing only lowercase characters). You need to print the repeated character whose first appearance is leftmost.The first line of input contains T denoting the number of testcases. T testcases follow.
Each testcase contains one line of input containing the string S.
Constraints:
1 <= T <= 100
1 <= |S| <= 1000For each testcase, in a new line, print the character. If not found then print "-1".Input:
2
geeksforgeeks
abcd
Output:
g
-1
Explanation:
Testcase1: We see that both e and g repeat as we move from left to right. But the leftmost is g so we print g.
Testcase2: No character repeats so we print -1.
, I have written this Solution Code: n=int(input())
while(n):
n-=1
string=input()
temp=True
for i in range(len(string)):
if(string[i] in string[i+1:] and i!=len(string)-1):
print(string[i])
temp=False
break
if(temp):
print(-1), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given a string S (containing only lowercase characters). You need to print the repeated character whose first appearance is leftmost.The first line of input contains T denoting the number of testcases. T testcases follow.
Each testcase contains one line of input containing the string S.
Constraints:
1 <= T <= 100
1 <= |S| <= 1000For each testcase, in a new line, print the character. If not found then print "-1".Input:
2
geeksforgeeks
abcd
Output:
g
-1
Explanation:
Testcase1: We see that both e and g repeat as we move from left to right. But the leftmost is g so we print g.
Testcase2: No character repeats so we print -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
signed main()
{
int t;
cin>>t;
while(t>0)
{
t--;
string s;
cin>>s;
map<char,int> ss;
int ch=-1;
for(int i=0;i<s.size();i++)
{
ss[s[i]]++;
}
for(int i=0;i<s.size();i++)
{
if(ss[s[i]]>=2)
{ ch=0;
cout<<s[i]<<endl;
break;
}
}
if(ch==-1) cout<<-1<<endl;
}
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given a string S (containing only lowercase characters). You need to print the repeated character whose first appearance is leftmost.The first line of input contains T denoting the number of testcases. T testcases follow.
Each testcase contains one line of input containing the string S.
Constraints:
1 <= T <= 100
1 <= |S| <= 1000For each testcase, in a new line, print the character. If not found then print "-1".Input:
2
geeksforgeeks
abcd
Output:
g
-1
Explanation:
Testcase1: We see that both e and g repeat as we move from left to right. But the leftmost is g so we print g.
Testcase2: No character repeats so we print -1.
, I have written this Solution Code: import java.io.*;
import java.util.*;
import java.lang.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0)
{
String str = sc.next();
int index = repeatedCharacter(str);
if(index == -1)
System.out.println("-1");
else
System.out.println(str.charAt(index));
}
}
static int repeatedCharacter(String S)
{
// Initialize leftmost index of every
// character as -1.
int firstIndex[]= new int[256];
for (int i = 0; i <256; i++)
firstIndex[i] = -1;
// Traverse from left and update result
// if we see a repeating character whose
// first index is smaller than current
// result.
int res = Integer.MAX_VALUE;
for (int i = 0; i < S.length(); i++) {
if (firstIndex[S.charAt(i)] == -1)
firstIndex[S.charAt(i)] = i;
else
res = Math.min(res, firstIndex[S.charAt(i)]);
}
return (res == Integer.MAX_VALUE) ? - 1 : res;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a string, your task is to calculate the number of different characters in that string.The first line of the input contains length of string. Second line contains String.
Constraints
1 <= string length <= 100
String contains only lowercase english lettersOutput a single integer which is the number of different character in the string.Sample Input
3
abc
Sample Output
3
Sample Input
7
asbscsb
Sample Output
4, I have written this Solution Code: n=int(input())
s=input()
l=set(s)
p=len(l)
print(p), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a string, your task is to calculate the number of different characters in that string.The first line of the input contains length of string. Second line contains String.
Constraints
1 <= string length <= 100
String contains only lowercase english lettersOutput a single integer which is the number of different character in the string.Sample Input
3
abc
Sample Output
3
Sample Input
7
asbscsb
Sample Output
4, I have written this Solution Code: import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String s = sc.next();
int cnt=0;
int p =0;
for(char ch = 'a';ch<='z';ch++){
p=0;
for(int i = 0;i<n;i++){
if(s.charAt(i)==ch){p=1;}
}
if(p==1){cnt++;}
}
System.out.println(cnt);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a string, your task is to calculate the number of different characters in that string.The first line of the input contains length of string. Second line contains String.
Constraints
1 <= string length <= 100
String contains only lowercase english lettersOutput a single integer which is the number of different character in the string.Sample Input
3
abc
Sample Output
3
Sample Input
7
asbscsb
Sample Output
4, I have written this Solution Code: #include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
string s;
cin>>s;
unordered_map<int,int> m;
for(int i=0;i<n;i++){
m[s[i]]++;
}
cout<<m.size();}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: If the total income in Wonderland is strictly more than 100 dollars, a tax of 10 dollars is deducted. Alice's total income is X dollars. She was wondering how much money will she get. Help Alice to find out.The first line of input will contain a single integer T, denoting the number of test cases. The first and only line of each test case contains a single integer X — Alice's total income.
<b>Constraints</b>
1 ≤ T ≤ 100
1 ≤ X ≤ 1000For each test case, output on a new line, the amount of money Alice gets.Sample Input :
4
5
105
101
100
Sample Output :
5
95
91
100, I have written this Solution Code: import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
while(x-->0){
int n = sc.nextInt();
if(n > 100){
System.out.println(n-10);
}
else{
System.out.println(n);
}
}
// your code goes here
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: If the total income in Wonderland is strictly more than 100 dollars, a tax of 10 dollars is deducted. Alice's total income is X dollars. She was wondering how much money will she get. Help Alice to find out.The first line of input will contain a single integer T, denoting the number of test cases. The first and only line of each test case contains a single integer X — Alice's total income.
<b>Constraints</b>
1 ≤ T ≤ 100
1 ≤ X ≤ 1000For each test case, output on a new line, the amount of money Alice gets.Sample Input :
4
5
105
101
100
Sample Output :
5
95
91
100, I have written this Solution Code: #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);
}
// operator overload of << for vector
template <typename T>
ostream &operator<<(ostream &os, const vector<T> &v) {
for (const auto &x : v)
os << x << " ";
return os;
}
int32_t main() {
ios_base::sync_with_stdio(true);
cin.tie(nullptr);
cout.tie(nullptr);
auto start = std::chrono::high_resolution_clock::now();
int tt;
cin >> tt;
while (tt--) {
int x;
cin >> x;
if (x > 100) {
cout << x - 10 << "\n";
} else {
cout << x << "\n";
}
}
auto stop = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(stop - start);
cerr << "Time taken : " << ((long double)duration.count()) / ((long double)1e9) << "s\n";
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: There are N robots standing in a row. Ultron wants to delegate a task of difficulty X to two of them. Each robot has its own ability, A[i] for the i<sup>th</sup> robot from the left. The task can only be completed if the sum of the abilities of the two robots is exactly equal to X. Ultron wants to find out the number of distinct unordered pairs of robots he can choose to complete this task. He wants to find this number for Q (not necessarily distinct) subarrays of robots.
Formally, for each query, you will be given two integers L and R and you need to calculate the number of pairs (i, j) such that L ≤ i < j ≤ R and A[i] + A[j] = X.
Further, these subarrays have a nice property that for every pair of them at least one of the following three statements hold:
1. Their intersection is one of the two intervals itself (for example, segments [2, 6] and [2, 4]).
2. Their intersection is empty (for example, segments [2, 6] and [7, 8]).
3. Their intersection consists of exactly one element (for example, segments [2, 5] and [5, 8]).
For another example, note that the segments [2, 5] and [4, 7] do not satisfy any of the above conditions, and thus cannot both appear in the input.
You need to find the answer to each one of Ultron's queries and report the XOR of their answers.
<b>Note:</b> Since the input is large, it is recommended that you use fast input/output methods.The first line of the input contains two space-separated integers, N, the number of robots and X, the difficulty of the task.
The second line contains N space-separated integers A[1], A[2], ... A[n] - the abilities of the robots.
The third line of input contains an integer Q - the number of queries Ultron has.
Q lines follow, the i<sup>th</sup> of them contains two integers L and R for the i<sup>th</sup> query.
It is guaranteed that the given subarrays satisfy the properties mentioned in the problem statement.
<b>Constraints: </b>
2 ≤ N ≤ 400000
1 ≤ X ≤ 1000000
0 ≤ A[i] ≤ X
1 ≤ Q ≤ 400000
1 ≤ L < R ≤ N for each queryPrint a single integer, the bitwise XOR of the answers of the Q queries.Sample Input:
7 10
2 9 1 8 4 4 6
5
1 7
2 5
1 6
3 4
4 5
Sample Output:
7
Explanation:
For the first query there are 4 pairs of indices, (2, 3), (1, 4), (5, 7), (6, 7).
For the second query there is 1 pair of indices, (2, 3)
Similarly you can verify that the answers for the five queries are (4, 1, 2, 0, 0) in order. So we print their bitwise XOR = 7.
, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
#define int long long
int X;
vector<int> adj[400005];
int ans[400005];
int cnt[1000005];
int A[400005];
pair<int, int> Q[400005];
void dfs(int x, bool keep = false)
{
int bigChild = -1, sz = 0;
for(auto &p: adj[x])
{
if(Q[p-1].second - Q[p-1].first > sz)
{
sz = Q[p-1].second - Q[p-1].first;
bigChild = p;
}
}
if(x > 0 && bigChild == -1)
{
for(int cur = Q[x-1].first; cur <= Q[x-1].second; cur++)
{
ans[x-1] += cnt[X-A[cur]];
cnt[A[cur]]++;
}
if(!keep)
{
for(int cur = Q[x-1].first; cur <= Q[x-1].second; cur++)
{
cnt[A[cur]]--;
}
}
return;
}
for(auto &p: adj[x])
{
if(p != bigChild)
{
dfs(p);
}
}
dfs(bigChild, true);
if(x > 0)
{
ans[x-1] = ans[bigChild-1];
for(int cur = Q[x-1].first; cur <= Q[x-1].second; cur++)
{
if(cur == Q[bigChild-1].first)
{
cur = Q[bigChild-1].second;
continue;
}
ans[x-1] += cnt[X-A[cur]];
cnt[A[cur]]++;
}
if(!keep)
{
for(int cur = Q[x-1].first; cur <= Q[x-1].second; cur++)
{
cnt[A[cur]]--;
}
}
}
}
bool my(int a, int b)
{
if(Q[a].first < Q[b].first) return true;
else if(Q[a].first == Q[b].first) return Q[a].second > Q[b].second;
return false;
}
void sack(int n, int q)
{
vector<int> order;
for(int i=0; i<q; i++) order.push_back(i);
sort(order.begin(), order.end(), my);
stack<int> right_ends;
stack<int> st;
for(int i=0; i<q; i++)
{
while(right_ends.size() && right_ends.top() <= Q[order[i]].first)
{
int which = st.top();
st.pop();
right_ends.pop();
if(st.empty())
{
adj[0].push_back(which+1);
}
else
{
adj[st.top()+1].push_back(which+1);
}
}
st.push(order[i]);
// cout << "inserting " << queries[i][2] << " into stack\n";
right_ends.push(Q[order[i]].second);
}
while(!st.empty())
{
int which = st.top();
st.pop();
right_ends.pop();
if(st.empty())
{
adj[0].push_back(which+1);
}
else
{
adj[st.top()+1].push_back(which+1);
}
}
// for(int i=0; i<=q; i++)
// {
// for(auto &x: adj[i])
// {
// cout << i << " has child " << x << "\n";
// }
// }
dfs(0);
}
signed main()
{
// freopen("input.txt", "r", stdin);
// freopen("output_sack.txt", "w", stdout);
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n >> X;
for(int i=0; i<n; i++)
{
cin >> A[i];
}
int q;
cin >> q;
for(int i=0; i<q; i++)
{
cin >> Q[i].first >> Q[i].second;
Q[i].first--;
Q[i].second--;
}
sack(n, q);
int ansr = 0;
for(int i=0; i<q; i++)
{
ansr ^= ans[i];
}
cout << ansr << "\n";
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Write a function called lucky_sevens which takes an array of integers and returns true if any three consecutive elements sum to 7An array containing numbers.Print true if such triplet exists summing to 7 else print falseSample input:-
[2, 1, 5, 1, 0]
[1, 6]
Sample output:-
true
false
Explanation:-
1+5+1 = 7
no 3 consecutive numbers so false, I have written this Solution Code: function lucky_sevens(arr) {
// if less than 3 elements then this challenge is not possible
if (arr.length < 3) {
console.log(false)
return;
}
// because we know there are at least 3 elements we can
// start the loop at the 3rd element in the array (i=2)
// and check it along with the two previous elements (i-1) and (i-2)
for (let i = 2; i < arr.length; i++) {
if (arr[i] + arr[i-1] + arr[i-2] === 7) {
console.log(true)
return;
}
}
// if loop is finished and no elements summed to 7
console.log(false)
}
, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Anya owns N triplets of integers (A<sub>i</sub>, B<sub>i</sub>, C<sub>i</sub>), for each i from 1 to N. She asks you to find a sequence of integers which satisfies the following conditions:
1. The sequence contains at least C<sub>i</sub> distinct integers from the closed interval [A<sub>i</sub>, B<sub>i</sub>], for each i from 1 to N.
2. Out of all sequences satisfying the first condition, choose a sequence with the minimum possible number of elements.
For simplicity, she asks you to just print the length of such a sequence.The first line of the input contains a single integer N denoting the number of triplets.
Then N lines follow, where the i<sup>th</sup> line contains three integers A<sub>i</sub>, B<sub>i</sub>, C<sub>i</sub> for each i from 1 to N.
<b> Constraints: </b>
1 ≤ N ≤ 2000
1 ≤ A<sub>i</sub> ≤ B<sub>i</sub> ≤ 2000
0 ≤ C<sub>i</sub> ≤ B<sub>i</sub> - A<sub>i</sub> + 1Print a single integer — the minimum possible sequence length.Sample Input 1:
1
1 3 3
Sample Output 1:
3
Sample Explanation 1:
Since there are only 3 elements in the closed interval [1,3], and we need to take 3 of them, clearly the smallest possible length is 3.
Sample Input 2:
2
1 3 1
3 5 1
Sample Output 2:
1
Sample Explanation 2:
We can take the sequence consisting of a single element {3}., I have written this Solution Code: l = [0]*2001
k = []
n = int(input())
for i in range(n):
a,b,c = map(int,input().split())
k.append([b,(a,c)])
k.sort()
for b,aa in k:
a = aa[0]
c = aa[1]
cnt = 0
for i in range(b,a-1,-1):
if l[i]:
cnt+=1
if cnt>=c:
continue
else:
for i in range(b,a-1,-1):
if not l[i]:
l[i]=1
cnt+=1
if cnt==c:
break
print(sum(l)), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Anya owns N triplets of integers (A<sub>i</sub>, B<sub>i</sub>, C<sub>i</sub>), for each i from 1 to N. She asks you to find a sequence of integers which satisfies the following conditions:
1. The sequence contains at least C<sub>i</sub> distinct integers from the closed interval [A<sub>i</sub>, B<sub>i</sub>], for each i from 1 to N.
2. Out of all sequences satisfying the first condition, choose a sequence with the minimum possible number of elements.
For simplicity, she asks you to just print the length of such a sequence.The first line of the input contains a single integer N denoting the number of triplets.
Then N lines follow, where the i<sup>th</sup> line contains three integers A<sub>i</sub>, B<sub>i</sub>, C<sub>i</sub> for each i from 1 to N.
<b> Constraints: </b>
1 ≤ N ≤ 2000
1 ≤ A<sub>i</sub> ≤ B<sub>i</sub> ≤ 2000
0 ≤ C<sub>i</sub> ≤ B<sub>i</sub> - A<sub>i</sub> + 1Print a single integer — the minimum possible sequence length.Sample Input 1:
1
1 3 3
Sample Output 1:
3
Sample Explanation 1:
Since there are only 3 elements in the closed interval [1,3], and we need to take 3 of them, clearly the smallest possible length is 3.
Sample Input 2:
2
1 3 1
3 5 1
Sample Output 2:
1
Sample Explanation 2:
We can take the sequence consisting of a single element {3}., I have written this Solution Code: //Author: Xzirium
//Time and Date: 00:28:35 28 December 2021
//Optional FAST
//#pragma GCC optimize("Ofast")
//#pragma GCC optimize("unroll-loops")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,fma,abm,mmx,avx,avx2,tune=native")
//Required Libraries
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/detail/standard_policies.hpp>
//Required namespaces
using namespace std;
using namespace __gnu_pbds;
//Required defines
#define endl '\n'
#define READ(X) cin>>X;
#define READV(X) long long X; cin>>X;
#define READAR(A,N) long long A[N]; for(long long i=0;i<N;i++) {cin>>A[i];}
#define rz(A,N) A.resize(N);
#define sz(X) (long long)(X.size())
#define pb push_back
#define pf push_front
#define fi first
#define se second
#define FORI(a,b,c) for(long long a=b;a<c;a++)
#define FORD(a,b,c) for(long long a=b;a>c;a--)
//Required typedefs
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_set1 = tree<T,null_type,greater<T>,rb_tree_tag,tree_order_statistics_node_update>;
typedef long long ll;
typedef long double ld;
typedef pair<int,int> pii;
typedef pair<long long,long long> pll;
//Required Constants
const long long inf=(long long)1e18;
const long long MOD=(long long)(1e9+7);
const long long INIT=(long long)(1e6+1);
const long double PI=3.14159265358979;
// Required random number generators
// mt19937 gen_rand_int(chrono::steady_clock::now().time_since_epoch().count());
// mt19937_64 gen_rand_ll(chrono::steady_clock::now().time_since_epoch().count());
//Required Functions
ll power(ll b, ll e)
{
ll r = 1ll;
for(; e > 0; e /= 2, (b *= b) %= MOD)
if(e % 2) (r *= b) %= MOD;
return r;
}
ll modInverse(ll a)
{
return power(a,MOD-2);
}
//Work
int main()
{
#ifndef ONLINE_JUDGE
if (fopen("INPUT.txt", "r"))
{
freopen ("INPUT.txt" , "r" , stdin);
//freopen ("OUTPUT.txt" , "w" , stdout);
}
#endif
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
clock_t clk;
clk = clock();
//-----------------------------------------------------------------------------------------------------------//
READV(N);
vector<pair<pll,ll>> Z;
FORI(i,0,N)
{
READV(a);
READV(b);
READV(c);
Z.pb({{b,a},c});
}
sort(Z.begin(),Z.end());
ordered_set1<ll> unused;
FORI(i,1,2001)
{
unused.insert(i);
}
ll ans=0;
FORI(i,0,N)
{
ll a=Z[i].fi.se;
ll b=Z[i].fi.fi;
ll c=Z[i].se;
ll curr=b-a+1-(unused.order_of_key(a-1)-unused.order_of_key(b));
while(curr<c)
{
ans++;
curr++;
auto it=unused.lower_bound(b);
unused.erase(it);
}
}
cout<<ans<<endl;
//-----------------------------------------------------------------------------------------------------------//
clk = clock() - clk;
cerr << fixed << setprecision(6) << "Time: " << ((double)clk)/CLOCKS_PER_SEC << endl;
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: In an exam of JEE one aspirant got P correct answers, Q wrong answer, and R unattempted question. If the mark for the correct answer is 4, for the wrong answer is -2, and for the unattempted questions is -1. Find the final marks the aspirant got.<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>Marks()</b> that takes integer P, Q, and R as arguments.
Constraints:-
0 <= P, Q, R <= 1000Return the final marks of each student.Sample Input:-
4 2 0
Sample Output:-
12
Sample Input:-
1 1 1
Sample Output:-
1, I have written this Solution Code: int Marks(int P, int Q, int R){
return 4*P - 2*Q - R;
}, In this Programming Language: C, Now tell me if this Code is compilable or not? | Compilable |
For this Question: In an exam of JEE one aspirant got P correct answers, Q wrong answer, and R unattempted question. If the mark for the correct answer is 4, for the wrong answer is -2, and for the unattempted questions is -1. Find the final marks the aspirant got.<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>Marks()</b> that takes integer P, Q, and R as arguments.
Constraints:-
0 <= P, Q, R <= 1000Return the final marks of each student.Sample Input:-
4 2 0
Sample Output:-
12
Sample Input:-
1 1 1
Sample Output:-
1, I have written this Solution Code: int Marks(int P, int Q, int R){
return 4*P - 2*Q - R;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: In an exam of JEE one aspirant got P correct answers, Q wrong answer, and R unattempted question. If the mark for the correct answer is 4, for the wrong answer is -2, and for the unattempted questions is -1. Find the final marks the aspirant got.<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>Marks()</b> that takes integer P, Q, and R as arguments.
Constraints:-
0 <= P, Q, R <= 1000Return the final marks of each student.Sample Input:-
4 2 0
Sample Output:-
12
Sample Input:-
1 1 1
Sample Output:-
1, I have written this Solution Code: def Marks(P,Q,R):
return 4*P-2*Q-R
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: In an exam of JEE one aspirant got P correct answers, Q wrong answer, and R unattempted question. If the mark for the correct answer is 4, for the wrong answer is -2, and for the unattempted questions is -1. Find the final marks the aspirant got.<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>Marks()</b> that takes integer P, Q, and R as arguments.
Constraints:-
0 <= P, Q, R <= 1000Return the final marks of each student.Sample Input:-
4 2 0
Sample Output:-
12
Sample Input:-
1 1 1
Sample Output:-
1, I have written this Solution Code: static int Marks(int P, int Q, int R){
return 4*P - 2*Q - R;
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Naruto and Sasuke are on a S- Rank mission. Now They got bored and thought of competing in a race against each other in a horizontal plane. They decides a common spot C at which both of them will try to reach. Whoever reaches first wins the race, both of them run at the same speed.
Given initial positions of Naruto and Sasuke as A and B recpectively.
you need to tell which of them will win the race. If Naruto wins print "N" ( without the quotes ), if Sasuke wins print "S" ( without the quotes ).
if both of them reach the common spot at the same time, print "D" (for draw, without the quotes ).<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>Race</b> that takes the integer A (initial position of Naruto) and B (initial position of Sasuke) and C (position of common spot) as parameter.
Constraints
1 <= A, B, C <= 100Return the character according to the given scenario.Sample Input
1 2 3
Sample Output
S
Sample Input
1 3 2
Sample Output
D, I have written this Solution Code:
char Race(int A, int B, int C){
if(abs(C-A)==abs(C-B)){return 'D';}
if(abs(C-A)>abs(C-B)){return 'S';}
else{
return 'N';}
}
, In this Programming Language: C, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Naruto and Sasuke are on a S- Rank mission. Now They got bored and thought of competing in a race against each other in a horizontal plane. They decides a common spot C at which both of them will try to reach. Whoever reaches first wins the race, both of them run at the same speed.
Given initial positions of Naruto and Sasuke as A and B recpectively.
you need to tell which of them will win the race. If Naruto wins print "N" ( without the quotes ), if Sasuke wins print "S" ( without the quotes ).
if both of them reach the common spot at the same time, print "D" (for draw, without the quotes ).<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>Race</b> that takes the integer A (initial position of Naruto) and B (initial position of Sasuke) and C (position of common spot) as parameter.
Constraints
1 <= A, B, C <= 100Return the character according to the given scenario.Sample Input
1 2 3
Sample Output
S
Sample Input
1 3 2
Sample Output
D, I have written this Solution Code: def Race(A,B,C):
if abs(C-A) ==abs(C-B):
return 'D'
if abs(C-A)>abs(C-B):
return 'S'
return 'N'
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Naruto and Sasuke are on a S- Rank mission. Now They got bored and thought of competing in a race against each other in a horizontal plane. They decides a common spot C at which both of them will try to reach. Whoever reaches first wins the race, both of them run at the same speed.
Given initial positions of Naruto and Sasuke as A and B recpectively.
you need to tell which of them will win the race. If Naruto wins print "N" ( without the quotes ), if Sasuke wins print "S" ( without the quotes ).
if both of them reach the common spot at the same time, print "D" (for draw, without the quotes ).<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>Race</b> that takes the integer A (initial position of Naruto) and B (initial position of Sasuke) and C (position of common spot) as parameter.
Constraints
1 <= A, B, C <= 100Return the character according to the given scenario.Sample Input
1 2 3
Sample Output
S
Sample Input
1 3 2
Sample Output
D, I have written this Solution Code:
char Race(int A, int B, int C){
if(abs(C-A)==abs(C-B)){return 'D';}
if(abs(C-A)>abs(C-B)){return 'S';}
else{
return 'N';}
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Naruto and Sasuke are on a S- Rank mission. Now They got bored and thought of competing in a race against each other in a horizontal plane. They decides a common spot C at which both of them will try to reach. Whoever reaches first wins the race, both of them run at the same speed.
Given initial positions of Naruto and Sasuke as A and B recpectively.
you need to tell which of them will win the race. If Naruto wins print "N" ( without the quotes ), if Sasuke wins print "S" ( without the quotes ).
if both of them reach the common spot at the same time, print "D" (for draw, without the quotes ).<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>Race</b> that takes the integer A (initial position of Naruto) and B (initial position of Sasuke) and C (position of common spot) as parameter.
Constraints
1 <= A, B, C <= 100Return the character according to the given scenario.Sample Input
1 2 3
Sample Output
S
Sample Input
1 3 2
Sample Output
D, I have written this Solution Code: static char Race(int A,int B,int C){
if(Math.abs(C-A)==Math.abs(C-B)){return 'D';}
if(Math.abs(C-A)>Math.abs(C-B)){return 'S';}
else{
return 'N';}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: To enter Todo's amusement park, there are M counters. Total N people want to enter the amusement park, each of whom will line up in front of one of the counters. Any counter worker gets angry if the number of people lining up in front of him is at least 2 more than the number of people lining up in front of any of its neighbouring counters. The worker at the K-th counter works the fastest.
Find the maximum number of people that can line up in front of the K-th counter such that each counter gets at least one person and no counter worker is angry.Input contains three integers M, N and K.
Constraints:
1 <= N <= 1000000000
1 <= M <= N
1 <= K <= MPrint the maximum number of people that can line up in front of the Kth counter such that each counter gets at least one person and no counter worker is angry.Sample Input 1
3 3 1
Sample Output 1
1
Explanation: Optimal Arrangement is 1 1 1.
Sample Input 2
3 6 1
Sample Output
3
Explanation: Optimal Arrangement is 3 2 1., I have written this Solution Code: import java.io.*;
class Main {
public static void main (String[] args) throws NumberFormatException, IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] s = in.readLine().split(" ");
in.close();
int M = Integer.parseInt(s[0]);
int N = Integer.parseInt(s[1]);
int K = Integer.parseInt(s[2]);
if(M>=N)
System.out.println(1);
else if(M == 1)
System.out.println(N);
else
System.out.println(countersAndLines(M, N, K));
}
static int countersAndLines (int m, int n, int k){
int start = n/m, end = (n/2)+1;
while(start<=end){
int mid = start+(end-start)/2;
long minPeople = option(mid, k) + option(mid, m-k+1) - mid;
if(minPeople == n)
return mid;
else if(minPeople < n)
start = mid+1;
else
end = mid-1;
}
return end;
}
static long sum (int m, int k, int i){
long sum = i;
int temp = --i;
for(int j = k-1; j>=1; j--){
if(i <= 1)
sum += 1;
else{
sum += i;
i--;
}
}
for(int j = k+1; j<=m; j++){
if(temp <= 1)
sum += 1;
else{
sum += temp;
temp--;
}
}
return sum;
}
static long option(int i, int k){
long x = k;
if(x > i)
x = i;
k -= x;
long y = k + x * (2 * i - x + 1) / 2;
return y;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: To enter Todo's amusement park, there are M counters. Total N people want to enter the amusement park, each of whom will line up in front of one of the counters. Any counter worker gets angry if the number of people lining up in front of him is at least 2 more than the number of people lining up in front of any of its neighbouring counters. The worker at the K-th counter works the fastest.
Find the maximum number of people that can line up in front of the K-th counter such that each counter gets at least one person and no counter worker is angry.Input contains three integers M, N and K.
Constraints:
1 <= N <= 1000000000
1 <= M <= N
1 <= K <= MPrint the maximum number of people that can line up in front of the Kth counter such that each counter gets at least one person and no counter worker is angry.Sample Input 1
3 3 1
Sample Output 1
1
Explanation: Optimal Arrangement is 1 1 1.
Sample Input 2
3 6 1
Sample Output
3
Explanation: Optimal Arrangement is 3 2 1., I have written this Solution Code: def get(ed, cnt):
d=cnt
if d>ed:
d=ed
cnt -=d
return cnt+d*(2*ed-d+1)/2
n,p,k = map(int,input().split())
l=1
r=10**9+10
while l+1<r:
m = (l+r)//2
if get(m,k) + get(m,n-k+1)-m>p:
r=m
else:
l=m
print(l), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: To enter Todo's amusement park, there are M counters. Total N people want to enter the amusement park, each of whom will line up in front of one of the counters. Any counter worker gets angry if the number of people lining up in front of him is at least 2 more than the number of people lining up in front of any of its neighbouring counters. The worker at the K-th counter works the fastest.
Find the maximum number of people that can line up in front of the K-th counter such that each counter gets at least one person and no counter worker is angry.Input contains three integers M, N and K.
Constraints:
1 <= N <= 1000000000
1 <= M <= N
1 <= K <= MPrint the maximum number of people that can line up in front of the Kth counter such that each counter gets at least one person and no counter worker is angry.Sample Input 1
3 3 1
Sample Output 1
1
Explanation: Optimal Arrangement is 1 1 1.
Sample Input 2
3 6 1
Sample Output
3
Explanation: Optimal Arrangement is 3 2 1., 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();
//////////////
typedef unsigned long long ull;
auto clk=clock();
#define all(x) x.begin(),x.end()
#define S second
#define F first
#define sz(x) ((long long)x.size())
#define int long long
#define f80 __float128
#define pii pair<int,int>
/////////////
ll get(ll ed, ll cnt){
ll d = cnt;
if (d > ed) d = ed;
cnt -= d;
return cnt + d * (2 * ed - d + 1) / 2;
}
signed main(){
#ifdef ANIKET_GOYAL
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
ll n, p, k; cin >> n >> p >> k;
ll l = 1, r = 1e9 + 10;
while(l + 1 < r){
ll m = (l + r) / 2;
if ( ull(get(m, k)) + get(m, n - k + 1) - m > p)
r = m;
else l = m;
}
cout << l << endl;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given three integers your task is to calculate the maximum integer among the given integers.<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>maxInteger()</b> that takes three integers a, b and c as a parameter.
<b>Constraint:</b>
1<=integers<=10000Print the maximum integer among the given integers.Sample Input:-
2 6 3
Sample Output:-
6
Sample Input:-
48 100 100
Sample Output:
100, I have written this Solution Code: def maxIntegers(x, y, z):
if(x >= y and x >= z):
print(x)
elif(y >= z and y >= x):
print(y)
else:
print(z), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of N elements. In the array, each element is present twice except for 1 element whose frequency in the array is 1. Hence the length of the array will always be odd.
Find the unique number.An integer, N, representing the size of the array. In the next line, N space-separated integers follow.
<b>Constraints:</b>
1 <= N <=10<sup>5</sup>
1 <= A[i] <=10<sup>8</sup>Output the element with frequency 1.Input :
5
1 1 2 2 3
Output:
3, 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 noofterm=Integer.parseInt(br.readLine());
int arr[] = new int[noofterm];
String s[] = br.readLine().split(" ");
for(int i=0; i<noofterm;i++){
arr[i]= Integer.parseInt(s[i]);
}
System.out.println(unique(arr));
}
public static int unique(int[] inputArray)
{
int result = 0;
for(int i=0;i<inputArray.length;i++)
{
result ^= inputArray[i];
}
return (result>0 ? result : -1);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of N elements. In the array, each element is present twice except for 1 element whose frequency in the array is 1. Hence the length of the array will always be odd.
Find the unique number.An integer, N, representing the size of the array. In the next line, N space-separated integers follow.
<b>Constraints:</b>
1 <= N <=10<sup>5</sup>
1 <= A[i] <=10<sup>8</sup>Output the element with frequency 1.Input :
5
1 1 2 2 3
Output:
3, I have written this Solution Code: n = int(input())
a = [int (x) for x in input().split()]
mapp={}
for index,val in enumerate(a):
if val in mapp:
del mapp[val]
else:
mapp[val]=1
for key, value in mapp.items():
print(key), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of N elements. In the array, each element is present twice except for 1 element whose frequency in the array is 1. Hence the length of the array will always be odd.
Find the unique number.An integer, N, representing the size of the array. In the next line, N space-separated integers follow.
<b>Constraints:</b>
1 <= N <=10<sup>5</sup>
1 <= A[i] <=10<sup>8</sup>Output the element with frequency 1.Input :
5
1 1 2 2 3
Output:
3, I have written this Solution Code: #include<bits/stdc++.h>
using namespace std;
signed main()
{
int n;
cin>>n;
int p=0;
for(int i=0;i<n;i++)
{
int a;
cin>>a;
p^=a;
}
cout<<p<<endl;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.