0% found this document useful (0 votes)
164 views39 pages

Coding Test 1 1: Array Game

The document contains code for solving three coding problems: 1. It contains code for finding the maximum rectangular area under a given histogram using a stack-based approach. This involves iterating through bars, calculating area with current bar as smallest bar using stack to find next smaller bar on left and right. 2. It contains code for finding the number of elements that appear odd number of times in an array using XOR and bitwise AND operations. 3. It contains code for solving a tourist problem using a segment tree to store maximum values in subtrees and find maximum values involving a given node.

Uploaded by

Gaurav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
164 views39 pages

Coding Test 1 1: Array Game

The document contains code for solving three coding problems: 1. It contains code for finding the maximum rectangular area under a given histogram using a stack-based approach. This involves iterating through bars, calculating area with current bar as smallest bar using stack to find next smaller bar on left and right. 2. It contains code for finding the number of elements that appear odd number of times in an array using XOR and bitwise AND operations. 3. It contains code for solving a tourist problem using a segment tree to store maximum values in subtrees and find maximum values involving a given node.

Uploaded by

Gaurav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 39

Coding test 1

1 Array Game

#include <bits/stdc++.h>
#define ll long long int
using namespace std;

int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n,m; cin>>n>>m; ll a[n],b[m],ans=0;
for(int i=0; i<n; i++) cin>>a[i];
for(int i=0; i<m; i++) cin>>b[i];
sort(a,a+n);
sort(b,b+m);
for(int i=0,j=m-1; i<n && j>=0; i++,j--){
if(a[i]<b[j]){
ans+=abs(a[i]-b[j]);
}
}
cout<<ans;
return 0;
}

2 Tourist
import java.util.*;
import java.io.*;

public class MainA


{
static InputReader in;
static PrintWriter out;
static int[][] g;
static int[] sub;
static int[] big;
static long ans;
static int K;
static int n;
static SegmentTree seg;
static int[] val;
static int maxX;
static int maxY;

public static class SegmentTree{


int st[];

SegmentTree(int n) {
st = new int[4*n];
}

public int getMid(int s, int e) {


return (s+e)>>1;
}

public int merge(int a,int b){


return Math.max(a, b);
}

public void update(int s, int e, int x, int y, int c, int si){


if(s == x && e == y){
st[si] = c;
}
else{
int mid = getMid(s, e);
if(y <= mid)
update(s, mid, x, y, c, 2*si);
else if(x > mid)
update(mid + 1, e, x ,y ,c ,2*si + 1);
else{
update(s, mid, x, mid, c, 2*si);
update(mid + 1, e, mid + 1, y, c, 2*si + 1);
}
st[si] = merge(st[2*si],st[2*si+1]);
}
}

public int get(int s, int e, int x, int y, int si){

if(s == x && e == y){


return st[si];
}
int mid = getMid(s, e);
if(y <= mid)
return get(s, mid, x, y, 2*si);
else if(x > mid)
return get(mid + 1, e, x, y, 2*si + 1);
return merge(get(s, mid, x, mid, 2*si), get(mid + 1, e, mid + 1, y, 2*si + 1));
}

public static void dfs(int u,int p){


sub[u] = 1;
for(int v : g[u]){
if(v == p) continue;
dfs(v,u);
sub[u] += sub[v];
}
}

static void add(int u,int p,int x){


seg.update(0, n - 1, u, u, x == 1? val[u]: 0, 1);
for(int v: g[u])
if(big[v] != 1 && v != p)
add(v, u, x);
}

static void trick(int u,int p,boolean k){


int mx = -1, b = 0;
for(int v: g[u]){
if(v == p) continue;
if(sub[v]>mx){
mx = sub[v];
b = v;
}
}

for(int v: g[u])
if(b != v && v != p)
trick(v,u,false);

if(mx != -1){
big[b] = 1;
trick(b,u,true);
}

add(u, p, 1);
if(u < K) {
val[u] = u == 0? 0: seg.get(0, n - 1, 0, u - 1, 1);
val[u]++;
}
else if(u > K) {
val[u] = u == n - 1? 0: seg.get(0, n - 1, u + 1, n - 1, 1);
val[u]++;
}
//debug(u,val[u]);
seg.update(0, n - 1, u, u, val[u], 1);
if(p == K) {
int x = (K == 0)? 0: seg.get(0, n - 1, 0, K - 1, 1);
int y = (K == n - 1)? 0: seg.get(0, n - 1, K + 1, n - 1, 1);
ans = Math.max(ans, maxX + y);
ans = Math.max(ans, maxY + x);
maxX = Math.max(maxX, x);
maxY = Math.max(maxY, y);
}

if(mx != -1) big[b] = 0;


if(!k) add(u, p, 0);
}

public static void solve()


{

InputReader in = new InputReader(System.in);


PrintWriter out = new PrintWriter(System.out);

n = in.nextInt();
K = in.nextInt() - 1;
sub = new int[n];
big = new int[n];
val = new int[n];
int[] u = new int[n - 1];
int[] v = new int[n - 1];
seg = new SegmentTree(n);

for(int i = 0;i < n - 1; i++){


u[i] = in.nextInt() - 1;
v[i] = in.nextInt() - 1;
}
g = graph(u, v, n);
dfs(K, -1);
trick(K, -1, false);

ans = Math.max(ans, maxX);


ans = Math.max(ans, maxY);
ans++;
out.println(ans);

out.close();
}

static int[][] graph(int from[], int to[], int n)


{
int g[][] = new int[n][];
int cnt[] = new int[n];
for (int i = 0; i < from.length; i++) {
cnt[from[i]]++;
cnt[to[i]]++;
}
for (int i = 0; i < n; i++) {
g[i] = new int[cnt[i]];
}
Arrays.fill(cnt, 0);
for (int i = 0; i < from.length; i++) {
g[from[i]][cnt[from[i]]++] = to[i];
g[to[i]][cnt[to[i]]++] = from[i];
}
return g;
}

public static void main(String[] args)


{
new Thread(null ,new Runnable(){
public void run()
{
try{
solve();
} catch(Exception e){
e.printStackTrace();
}
}
},"1",1<<26).start();
}

static class Pair implements Comparable<Pair>


{

int x,y;
int l,r;

Pair (int x, int y, int l, int r)


{
this.x = x;
this.y = y;
this.l = l;
this.r = r;
}

public int compareTo(Pair o)


{
if(this.l == o.l)
return Integer.compare(this.r, o.r);
return Integer.compare(this.l, o.l);
}

@Override
public String toString()
{
return x + " "+ y + " "+l + " " + r;
}

static void debug(Object... o)


{
System.out.println(Arrays.deepToString(o));
}

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 long[] nextLongArray(int n)


{
long a[] = new long[n];
for (int i = 0; i < n; i++)
{
a[i] = nextLong();
}
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);
}

}
}

Coding test 2
1. Acche Din

import java.io.*;
import java.util.*;

public class TestClass {


public static void main(String args[] ) throws Exception {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(input.readLine());
while(t-- > 0){
int n = Integer.parseInt(input.readLine());
StringTokenizer st = new StringTokenizer(input.readLine()," ");
int [] a = new int[n];
for(int i=0;i<n;i++){
a[i] = Integer.parseInt(st.nextToken());
}
int once =0;
int twice =0;
for(int i=0;i<n;i++){
twice = twice | once&a[i];
once = once^a[i];
int common = once&twice;
once = once & (~common);
twice = twice & (~common);
}
System.out.println(once);
}
input.close();
}
}

CODING TEST 3
1 RECTANGULAR AREA
import java.util.Stack;

public class RectArea


{
// The main function to find the maximum rectangular area under given
// histogram with n bars
static int getMaxArea(int hist[], int n)
{
// Create an empty stack. The stack holds indexes of hist[] array
// The bars stored in stack are always in increasing order of their
// heights.
Stack<Integer> s = new Stack<>();

int max_area = 0; // Initialize max area


int tp; // To store top of stack
int area_with_top; // To store area with top bar as the smallest bar

// Run through all bars of given histogram


int i = 0;
while (i < n)
{
// If this bar is higher than the bar on top stack, push it to stack
if (s.empty() || hist[s.peek()] <= hist[i])
s.push(i++);

// If this bar is lower than top of stack, then calculate area of rectangle
// with stack top as the smallest (or minimum height) bar. 'i' is
// 'right index' for the top and element before top in stack is 'left index'
else
{
tp = s.peek(); // store the top index
s.pop(); // pop the top
// Calculate the area with hist[tp] stack as smallest bar
area_with_top = hist[tp] * (s.empty() ? i : i - s.peek() - 1);

// update max area, if needed


if (max_area < area_with_top)
max_area = area_with_top;
}
}

// Now pop the remaining bars from stack and calculate area with every
// popped bar as the smallest bar
while (s.empty() == false)
{
tp = s.peek();
s.pop();
area_with_top = hist[tp] * (s.empty() ? i : i - s.peek() - 1);

if (max_area < area_with_top)


max_area = area_with_top;
}

return max_area;

// Driver program to test above function


public static void main(String[] args)
{
int hist[] = { 6, 2, 5, 4, 5, 1, 6 };
System.out.println(getMaxArea(hist, hist.length));
}
}

2. SUMITA AND EQUAL ARRAY

#include<stdio.h>
int gcd(int a,int b)
{
if(a==0)
{
return b;
}
return gcd(b%a,a);
}
int main()
{
int t,i,n,x,y,z,arr[100000],j,a;
scanf("%d",&t);
for(i=0;i<=t-1;i++)
{int count=0;
scanf("%d %d %d %d",&n,&x,&y,&z);
for(j=0;j<=n-1;j++)
{
scanf("%d",&arr[j]);
if(j==0)
{
a=arr[j];
}
else
a=gcd(a,arr[j]);
}
for(j=0;j<=n-1;j++)
{arr[j]=arr[j]/a;
while(arr[j]%x==0)
{
arr[j]=arr[j]/x;
}
while(arr[j]%y==0)
{
arr[j]=arr[j]/y;
}
while(arr[j]%z==0)
{
arr[j]=arr[j]/z;
}
if(arr[j]>1)
{
count++;
break;
}
}
if(count==0)
{
printf("She can\n");
}
else
{
printf("She can't\n");
}
}
return 0;
}

3. RANK LIST

import java.io.BufferedReader;
import java.io.InputStreamReader;

//import for Scanner and other utility classes


import java.util.*;

public class TestClass {


public static void main(String args[] ) throws Exception {
//BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int N = Integer.parseInt(line);

LinkedList<Student> list = new LinkedList();


for (int i = 0; i < N; i++) {
String[] split = br.readLine().split(" ");
list.add(new Student(split[0], Integer.parseInt(split[1]), Integer.parseInt(split[2])));
}

Collections.sort(list, new Comparator<Student>() {


@Override
public int compare(Student s1, Student s2) {
int c = s2.marks-(s1.marks);

if(c==0) {
c = s1.name.compareTo(s2.name);
}
if(c==0) {
c= s1.scholar-(s2.scholar);
}

return c;
}
});

for(Student s: list)
System.out.println(s);
}
}

class Student {
String name;
int scholar;
int marks;
public Student(String name, int scholar, int marks){
this.name = name;
this.scholar = scholar;
this.marks = marks;
}

public String toString() {


return this.name+" "+this.scholar+" "+this.marks;
}

@Override
public boolean equals(Object o) {
if(this==o)
return true;

if(o instanceof Student) {


Student tmp = (Student) o;
if(name.equals(tmp.name) && scholar == tmp.scholar)
return true;
}

return false;
}

@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * scholar;
result = prime * (name.hashCode()) + result;
return result;
}
}

CODING TEST 4

1. Capital of hills
#include<bits/stdc++.h>
using namespace std;

typedef long long int ll;


typedef long double ld;
typedef unsigned long long ull;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef pair<ll,ll> pll;
typedef vector<pll> vpll;

#define ff first
#define ss second
#define pb push_back
#define mp make_pair
#define mt make_tuple
#define eb emplace_back
#define fr(i,n) for(ll i = 0; i < n; ++i)
#define frs(i,s,n) for(ll i = s; i < n; ++i)
#define frb(i,s,e) for(ll i = s; i <= e; ++i)
#define rfr(i,n) for(ll i = n-1; i >= 0; i--)
#define frbr(i,e,s) for(ll i = e; i >= s; i--)
#define all(x) (x).begin(), (x).end()
#define sz(x) ((ll)(x).size())

template <typename A, typename B>


string to_string(pair<A, B> p);

template <typename A, typename B, typename C>


string to_string(tuple<A, B, C> p);

template <typename A, typename B, typename C, typename D>


string to_string(tuple<A, B, C, D> p);

string to_string(const string& s)


{
return '"' + s + '"';
}

string to_string(const char* s)


{
return to_string((string) s);
}

string to_string(bool b)
{
return (b ? "true" : "false");
}

string to_string(vector<bool> v)
{
bool first = true;
string res = "{";
for(int i = 0; i < static_cast<int>(v.size()); i++)
{
if(!first)
res += ", ";
first = false;
res += to_string(v[i]);
}
res += "}";
return res;
}

template <size_t N>


string to_string(bitset<N> v)
{
string res = "";
for(size_t i = 0; i < N; i++)
res += static_cast<char>('0' + v[i]);
return res;
}

template <typename A>


string to_string(A v)
{
bool first = true;
string res = "{";
for(const auto &x : v)
{
if(!first)
res += ", ";
first = false;
res += to_string(x);
}
res += "}";
return res;
}
template <typename A, typename B>
string to_string(pair<A, B> p)
{
return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}

template <typename A, typename B, typename C>


string to_string(tuple<A, B, C> p)
{
return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) +
")";
}

template <typename A, typename B, typename C, typename D>


string to_string(tuple<A, B, C, D> p)
{
return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) +
", " + to_string(get<3>(p)) + ")";
}

void debugOut() { cerr << "]\n"; }

template <typename Head, typename... Tail>


void debugOut(Head H, Tail... T)
{
cerr << to_string(H);
if(sizeof...(T))
cerr << ", ";
debugOut(T...);
}

clock_t start_time = clock();


double getCurrentTime()
{
return ((double)(clock() - start_time)) / CLOCKS_PER_SEC;
}

#ifdef LOCAL
#define dbg(...) {cerr << "[" << #__VA_ARGS__ << "] = [", debugOut(__VA_ARGS__);}
#define dbg_arr(a,n) {cerr << "[" << #a << "] = [ "; fr(i,n) cerr << a[i] << " "; cerr << "]\n";}
#define dbg_mat(m,r,c) {cerr << "[" << #m << "]:\n"; fr(i,r) {cerr << "[ "; fr(j,c) cerr << m[i][j]
<< " "; cerr << "]\n";}}
#define dbg_time() {cerr << "\n" << "Time elapsed: " << getCurrentTime() << "\n\n\n";}
#else
#define dbg(x...) {}
#define dbg_arr(a,n) {}
#define dbg_mat(m,r,c) {}
#define dbg_time() {}
#endif
const ld PI = acos(-1);
const ld EPS = 1e-9;
const ll INF = 1e18;
const ll SINF = 1e9;
const ll MOD = 1e9+7; // 998244353;
const ll MAX = 100100;

void pre()
{
// factorizer::sieve();
// prepare_factorials();
}

void solve()
{
ll n; cin >> n;
ll arr[n];
fr(i, n)
cin>>arr[i];
vl temp(n, 0);
ll ans = 0;
stack < ll > st; // stictly decreasing
fr(i, n)
{
if(st.empty())
st.push(i);
else
{
while(!st.empty() && (arr[i] >= arr[st.top()]))
{
if(arr[i] == arr[st.top()]) // equal towards left
{
temp[i] = temp[st.top()] + 1;
ans += temp[i];
}
else // less towards left
ans += temp[st.top()] + 1;
st.pop();
}
// high towards left
if(!st.empty())
ans++;
st.push(i);
}
}
cout << ans << "\n";
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);

// cout << fixed << setprecision(15);

#ifdef LOCAL
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif

pre();

ll t = 1;
// cin >> t;
frb(CASE, 1, t)
{
// cout << "Case #" << CASE << ": ";
// dbg(CASE);
solve();
}

dbg_time();

return 0;
}

2. MAGIC SQUARE

#include <bits/stdc++.h>

using namespace std;


int cal(vector<vector<int>> m,vector<vector<int>> s)
{
int i,j,corr=0;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(m[i][j]!=s[i][j])
{
corr+=abs(m[i][j]-s[i][j]);
}
}
}
return corr;
}
vector<vector<int>> tran(vector<vector<int>> s)
{
vector<vector<int>> ans(s.begin(),s.end());
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
ans[i][j]=(s[j][i]);
}
}
return ans;
}
// Complete the formingMagicSquare function below.
int formingMagicSquare(vector<vector<int>> s)
{
vector<vector<int>> m1={{2,7,6},{9,5,1},{4,3,8}};
vector<vector<int>> m2={{6,1,8},{7,5,3},{2,9,4}};
vector<vector<int>> m3={{8,3,4},{1,5,9},{6,7,2}};
vector<vector<int>> m4={{4,9,2},{3,5,7},{8,1,6}};
int ans;
ans=cal(m4,s);
ans=min(ans,cal(tran(m4),s));
ans=min(ans,cal(m3,s));
ans=min(ans,cal(tran(m3),s));
ans=min(ans,cal(m2,s));
ans=min(ans,cal(tran(m2),s));
ans=min(ans,cal(m1,s));
ans=min(ans,cal(tran(m1),s));

return ans;
}

int main()
{
vector<vector<int>> s(3);
for (int i = 0; i < 3; i++) {
s[i].resize(3);

for (int j = 0; j < 3; j++) {


cin >> s[i][j];
}

int result = formingMagicSquare(s);

cout << result << "\n";

return 0;
}

3. MANCUNIAN AND FANTABOLOUS PAIR

import sys

def numFab(arr, n):


rights = [-1] * n
lefts = [-1] * n

st = [n - 1]
for i in range(n - 2, -1, -1):
while st and arr[st[-1]] < arr[i]:
st.pop()

if st:
rights[i] = st[-1]

st.append(i)

st =[0]

for i in range(1, n, 1):


while st and arr[st[-1]] < arr[i]:
st.pop()

if st:
lefts[i] = st[-1]

st.append(i)

res = [0] * n

for i in range(n):
if rights[i] != -1:
res[rights[i] - i] = max([res[rights[i] - i], i - lefts[i]])

return sum(res)
n = int(input())
arr = list(map(int, sys.stdin.readline().split()))

if n <= 1:
print(0)

else:
count = numFab(arr, n)
print(count)

CODING TEST 5

1. AKSHI_PROBLEM

T = int(input())
for p in range (T):
N = int(input())
A = [int (x) for x in reversed(list(map(int, input().split())))]
for i in range (N):
print(A[i], end=' ')
print()

2. VOWEL RECOGNITION

#include<iostream>
#include<string>

using namespace std;

#define int long long

int32_t main()
{
int t;
cin>>t;

while(t--)
{
string s;
cin>>s;

int dp[s.length()];
int sum = 0;
for(int i = 0; i<s.length(); i++)
{
if(i==0)
dp[i]=s.length();
else
dp[i] = dp[i-1]+s.length()-(2*i);

for(int i = 0; i<s.length(); i++)


{
if(s[i]=='a' || s[i]=='A' || s[i]=='e' || s[i]=='E' || s[i]=='i' || s[i]=='I' || s[i]=='o' || s[i]=='O' ||
s[i]=='u' || s[i]=='U' )
{
sum = sum + dp[i];
}
}

cout<<sum<<"\n";

}
return 0;
}

CODING TEST 6

1. BALANCED STRINGS

from sys import stdin


from collections import Counter

def balanced_strings():
for _ in range(int(stdin.readline())):
string = stdin.readline().strip()
xor = 0
A = [0]
for i in string:
xor = xor ^ (1<<(ord(i)-97))
A.append(xor)
counter = Counter(A)
yield sum(map(lambda n: n*(n-1)//2,counter.values()))

def main():
print(*balanced_strings(),sep = "\n")

if __name__ == "__main__":
main()

2. SORT NUMBERS

import java.util.*;
import java.util.Scanner;
public class ArrayListDescendingSort {
public static void main(String args[]) {
int n,t;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
ArrayList<Integer> arraylist = new ArrayList<Integer>();
for(int i=0;i<n;i++)
{
t=sc.nextInt();
arraylist.add(t);
}

/* Sorting in decreasing (descending) order*/


Collections.sort(arraylist, Collections.reverseOrder());

/* Sorted List in reverse order*/

for(Integer str: arraylist){


System.out.println(str);
}
}
}

CODING TEST 7

2 SUMITA AND EQUAL ARRAY


#include<iostream>
using namespace std;
#define ll long long
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
ll t;
cin>>t;
while(t--)
{
int x,y,z,n;
cin>>n>>x>>y>>z;

int b=0;
int flag=1;
for(int i=0; i<n; i++)
{
int a;
cin>>a;
while(a%x==0) a/=x;

while(a%y==0) a/=y;

while(a%z==0) a/=z;

if(i>1&&a!=b)
{
flag=0;
// break;
}

b=a;
}

if(flag)
cout<<"She can"<<endl;
else
cout<<"She can't"<<endl;

return 0;
}

CODING TEST 8
1. LIFE MATRIX

'''
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT

# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
'''
from collections import deque
def counter(matrix,next_to_visit,list_1,N,M):
counter = 0
waiting = deque([1])
while waiting:
counter += 1
waiting = deque()
while next_to_visit:
i,j = next_to_visit.popleft()
for m,n in [(i+1,j),(i,j-1),(i,j+1),(i-1,j)]:
if 0<=m<N and 0<=n<M:
if matrix[m][n] == 1:
matrix[m][n] = 2
waiting.append((m,n))
list_1 -= 1
next_to_visit = waiting
if list_1:
return -1
return counter-1

N,M = map(int,input().split())
matrix = list()
next_to_visit = deque()
list_1 = 0
for i in range(N):
try:
matrix.append(list(map(int,input().split())))
except EOFError:
continue

for i in range(0,N):
for j in range(0,M):
try:
if matrix[i][j] == 2:
next_to_visit.append((i,j))
elif matrix[i][j] == 1:
list_1 += 1
except IndexError:
pass

try:
print(counter(matrix,next_to_visit,list_1,N,M))
except IndexError:
print(999)

2. CAPITAL OF HILLS

'''
# Sample code to perform I/O:

name = input() # Reading input from STDIN


print('Hi, %s.' % name) # Writing output to STDOUT

# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
'''

# Write your code here


n = int(input())
total = 0
previous = None
total_smaller = 0
stack = []
for x in input().split():
count = 0
num = int(x)
while stack:
if stack[-1][0] < num:
count += stack.pop()[1]
else:
break

if stack:
if stack[-1][0] == num:
count += stack[-1][1]
stack[-1][1] += 1
if len(stack)>1:
count += 1
else:
count += 1
stack.append([num,1])
else:
stack.append([num,1])
total += count
#print(stack)
print(total)

CODING TEST 9

1. NITISH AND PILLARS


#include<bits/stdc++.h>
using namespace std;
#define int long long
#define fast() ios_base::sync_with_stdio(0);cin.tie(0)
#define all(x) x.begin(),x.end()
#define pb push_back
int32_t main()
{int n,i,cur,q,l,r,x;
stack<int> stk;
fast();
cin>>n;
vector<int> a(n),v[n],nge(n);
for(i=0;i<n;++i)
cin>>a[i];
for(i=0;i<n;++i)
{while(!stk.empty() && a[stk.top()]<a[i])
nge[stk.top()]=i,stk.pop();
stk.push(i);
}
while(!stk.empty())
nge[stk.top()]=-1,stk.pop();
/*for(auto x:nge)
cout<<x<<" ";
cout<<"\n";
*/
for(i=0;i<n;++i)
{cur=i;
while(cur!=-1 && nge[cur]<n)
v[i].pb(cur),cur=nge[cur];
v[i].pb(n);
}
/*cout<<"\n";
for(i=0;i<n;++i)
{cout<<i<<": ";
for(auto x:v[i])
cout<<x<<" ";
cout<<"\n";
}*/
cin>>q;
for(;q;--q)
{cin>>l>>r;
x=upper_bound(all(v[l]),r)-v[l].begin();
cout<<x<<"\n";
}
return 0;
}

2. CAN YOU SOLVE IT

'''
# Sample code to perform I/O:

name = input() # Reading input from STDIN


print('Hi, %s.' % name) # Writing output to STDOUT

# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
'''

def find(arr, n):


l1 = [v-i for i, v in enumerate(arr)]
l2 = [v+i for i, v in enumerate(arr)]
return max(max(l1) - min(l1), max(l2) - min(l2))
if __name__ == "__main__":
for i in range(int(input())):
n = int(input())
l = list(map(int, input().split()))

print(find(l, n))

CODING TEST 10

1. WRONG BALL

import java.util.*;
import java.lang.*;
import java.io.*;

public class GFG {


public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
while(t-- > 0){
String s = scan.next();
int c=0;
for(int i=0;i<s.length();i++){
if(i%2 == 1 && s.charAt(i)=='R')
c++;
else if(i%2 == 0 && s.charAt(i)=='B')
c++;
}
System.out.println(c);
}
}
}
2. BALANCED STRINGS
from sys import stdin
from collections import Counter

def balanced_strings():
for _ in range(int(stdin.readline())):
string = stdin.readline().strip()
xor = 0
A = [0]
for i in string:
xor = xor ^ (1<<(ord(i)-97))
A.append(xor)
counter = Counter(A)
yield sum(map(lambda n: n*(n-1)//2,counter.values()))

def main():
print(*balanced_strings(),sep = "\n")

if __name__ == "__main__":
main()

You might also like