#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void dfs(int node, int parent, const vector<vector<int>> &adj, const vector<int> &A, int length, int &maxLength) {
maxLength = max(maxLength, length);
for (int neighbor : adj[node]) {
if (neighbor == parent) continue;
if ((A[node] ^ A[neighbor]) < min(A[node], A[neighbor])) {
dfs(neighbor, node, adj, A, length + 1, maxLength);
}
}
}
int main() {
int N;
cin >> N;
vector<int> A(N), P(N);
for (int i = 0; i < N; ++i) cin >> A[i];
for (int i = 1; i < N; ++i) cin >> P[i];
vector<vector<int>> adj(N);
for (int i = 1; i < N; ++i) {
int parent = P[i];
adj[parent].push_back(i);
adj[i].push_back(parent);
}
int maxLength = 0;
dfs(0, -1, adj, A, 1, maxLength);
cout << maxLength << endl;
return 0;
}
Nodes
#include <vector>
#include <algorithm>
using namespace std;
void dfs(int node, int parent, const vector<vector<int>> &adj, const vector<int> &A, int length, int &maxLength) {
maxLength = max(maxLength, length);
for (int neighbor : adj[node]) {
if (neighbor == parent) continue;
if ((A[node] ^ A[neighbor]) < min(A[node], A[neighbor])) {
dfs(neighbor, node, adj, A, length + 1, maxLength);
}
}
}
int main() {
int N;
cin >> N;
vector<int> A(N), P(N);
for (int i = 0; i < N; ++i) cin >> A[i];
for (int i = 1; i < N; ++i) cin >> P[i];
vector<vector<int>> adj(N);
for (int i = 1; i < N; ++i) {
int parent = P[i];
adj[parent].push_back(i);
adj[i].push_back(parent);
}
int maxLength = 0;
dfs(0, -1, adj, A, 1, maxLength);
cout << maxLength << endl;
return 0;
}
Nodes
👍1
#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <algorithm>
using namespace std;
int maxTreeScore(int node_count, int edge_count, vector<pair<int, int>>& edges, vector<int>& colors) {
// Step 1: Parse input and create adjacency list
unordered_map<int, vector<int>> adjacency_list;
for (const auto& edge : edges) {
int start = edge.first;
int end = edge.second;
adjacency_list[start].push_back(end);
adjacency_list[end].push_back(start);
}
// Step 2: Calculate depth of each node using BFS
vector<int> node_depth(node_count + 1, -1);
node_depth[1] = 0;
queue<int> bfs_queue;
bfs_queue.push(1);
while (!bfs_queue.empty()) {
int current_node = bfs_queue.front();
bfs_queue.pop();
int current_depth = node_depth[current_node];
for (int neighbor : adjacency_list[current_node]) {
if (node_depth[neighbor] == -1) { // unvisited
node_depth[neighbor] = current_depth + 1;
bfs_queue.push(neighbor);
}
}
}
// Step 3: Group nodes by depth
unordered_map<int, vector<int>> nodes_grouped_by_depth;
for (int node = 1; node <= node_count; ++node) {
nodes_grouped_by_depth[node_depth[node]].push_back(node);
}
// Step 4: Calculate distinct colors per depth
unordered_map<int, int> distinct_colors_at_depth;
for (const auto& pair : nodes_grouped_by_depth) {
int depth = pair.first;
const vector<int>& nodes = pair.second;
unordered_set<int> unique_colors;
for (int node : nodes) {
unique_colors.insert(colors[node - 1]);
}
distinct_colors_at_depth[depth] = unique_colors.size();
}
// Step 5: Dynamic programming to calculate max score
int max_depth = max_element(nodes_grouped_by_depth.begin(), nodes_grouped_by_depth.end(),
[](const auto& a, const auto& b) {
return a.first < b.first;
})->first;
vector<int> dp_score(max_depth + 2, 0);
for (int depth = max_depth; depth >= 0; --depth) {
// Option 1: Move to the next depth without adding score
dp_score[depth] = dp_score[depth + 1];
// Option 2: Add the distinct colors to score and move to depth depth + unique_colors_count
if (distinct_colors_at_depth.find(depth) != distinct_colors_at_depth.end()) {
int unique_colors_count = distinct_colors_at_depth[depth];
if (depth + unique_colors_count <= max_depth) {
dp_score[depth] = max(dp_score[depth], dp_score[depth + unique_colors_count] + unique_colors_count);
} else {
dp_score[depth] = max(dp_score[depth], unique_colors_count);
}
}
}
return dp_score[0];
}
diving in a tree , all test cases are passing
@allcoding1
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <algorithm>
using namespace std;
int maxTreeScore(int node_count, int edge_count, vector<pair<int, int>>& edges, vector<int>& colors) {
// Step 1: Parse input and create adjacency list
unordered_map<int, vector<int>> adjacency_list;
for (const auto& edge : edges) {
int start = edge.first;
int end = edge.second;
adjacency_list[start].push_back(end);
adjacency_list[end].push_back(start);
}
// Step 2: Calculate depth of each node using BFS
vector<int> node_depth(node_count + 1, -1);
node_depth[1] = 0;
queue<int> bfs_queue;
bfs_queue.push(1);
while (!bfs_queue.empty()) {
int current_node = bfs_queue.front();
bfs_queue.pop();
int current_depth = node_depth[current_node];
for (int neighbor : adjacency_list[current_node]) {
if (node_depth[neighbor] == -1) { // unvisited
node_depth[neighbor] = current_depth + 1;
bfs_queue.push(neighbor);
}
}
}
// Step 3: Group nodes by depth
unordered_map<int, vector<int>> nodes_grouped_by_depth;
for (int node = 1; node <= node_count; ++node) {
nodes_grouped_by_depth[node_depth[node]].push_back(node);
}
// Step 4: Calculate distinct colors per depth
unordered_map<int, int> distinct_colors_at_depth;
for (const auto& pair : nodes_grouped_by_depth) {
int depth = pair.first;
const vector<int>& nodes = pair.second;
unordered_set<int> unique_colors;
for (int node : nodes) {
unique_colors.insert(colors[node - 1]);
}
distinct_colors_at_depth[depth] = unique_colors.size();
}
// Step 5: Dynamic programming to calculate max score
int max_depth = max_element(nodes_grouped_by_depth.begin(), nodes_grouped_by_depth.end(),
[](const auto& a, const auto& b) {
return a.first < b.first;
})->first;
vector<int> dp_score(max_depth + 2, 0);
for (int depth = max_depth; depth >= 0; --depth) {
// Option 1: Move to the next depth without adding score
dp_score[depth] = dp_score[depth + 1];
// Option 2: Add the distinct colors to score and move to depth depth + unique_colors_count
if (distinct_colors_at_depth.find(depth) != distinct_colors_at_depth.end()) {
int unique_colors_count = distinct_colors_at_depth[depth];
if (depth + unique_colors_count <= max_depth) {
dp_score[depth] = max(dp_score[depth], dp_score[depth + unique_colors_count] + unique_colors_count);
} else {
dp_score[depth] = max(dp_score[depth], unique_colors_count);
}
}
}
return dp_score[0];
}
diving in a tree , all test cases are passing
@allcoding1
👍2
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
const int MOD = 1000000007;
int minLampsToLightRoad(int num_positions, int num_lamps, vector<int>& lamp_positions, vector<int>& left_reach, vector<int>& right_reach, vector<pair<int, int>>& queries) {
// Step 1: Create intervals for each lamp
vector<pair<int, int>> intervals;
for (int i = 0; i < num_lamps; ++i) {
intervals.push_back({lamp_positions[i] - left_reach[i], lamp_positions[i] + right_reach[i]});
}
// Step 2: Sort intervals based on starting position
sort(intervals.begin(), intervals.end());
// Precompute the farthest reach for each starting point
vector<pair<int, int>> max_reach_from_start;
int current_max_reach = -1;
for (const auto& interval : intervals) {
int start = interval.first;
int end = interval.second;
if (max_reach_from_start.empty() start > max_reach_from_start.back().first) {
max_reach_from_start.push_back({start, end});
}
current_max_reach = max(current_max_reach, end);
max_reach_from_start.back().second = current_max_reach;
}
auto min_lamps_needed = [&](int query_left, int query_right) {
int count = 0;
int max_reach = query_left;
while (max_reach <= query_right) {
auto it = upper_bound(max_reach_from_start.begin(), max_reach_from_start.end(), make_pair(max_reach, INT_MAX));
if (it == max_reach_from_start.begin() prev(it)->first > max_reach) {
return -1;
}
int next_max_reach = prev(it)->second;
if (next_max_reach <= max_reach) {
return -1;
}
max_reach = next_max_reach + 1;
count++;
if (max_reach > query_right) {
break;
}
}
return max_reach > query_right ? count : -1;
};
// Step 3: Process each query and sum up the results
int result_sum = 0;
for (const auto& query : queries) {
int result = min_lamps_needed(query.first, query.second);
if (result != -1) {
result_sum += result;
result_sum %= MOD;
}
}
return result_sum;
}
lightning lamp code , all cases are passing
@allcoding1
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
const int MOD = 1000000007;
int minLampsToLightRoad(int num_positions, int num_lamps, vector<int>& lamp_positions, vector<int>& left_reach, vector<int>& right_reach, vector<pair<int, int>>& queries) {
// Step 1: Create intervals for each lamp
vector<pair<int, int>> intervals;
for (int i = 0; i < num_lamps; ++i) {
intervals.push_back({lamp_positions[i] - left_reach[i], lamp_positions[i] + right_reach[i]});
}
// Step 2: Sort intervals based on starting position
sort(intervals.begin(), intervals.end());
// Precompute the farthest reach for each starting point
vector<pair<int, int>> max_reach_from_start;
int current_max_reach = -1;
for (const auto& interval : intervals) {
int start = interval.first;
int end = interval.second;
if (max_reach_from_start.empty() start > max_reach_from_start.back().first) {
max_reach_from_start.push_back({start, end});
}
current_max_reach = max(current_max_reach, end);
max_reach_from_start.back().second = current_max_reach;
}
auto min_lamps_needed = [&](int query_left, int query_right) {
int count = 0;
int max_reach = query_left;
while (max_reach <= query_right) {
auto it = upper_bound(max_reach_from_start.begin(), max_reach_from_start.end(), make_pair(max_reach, INT_MAX));
if (it == max_reach_from_start.begin() prev(it)->first > max_reach) {
return -1;
}
int next_max_reach = prev(it)->second;
if (next_max_reach <= max_reach) {
return -1;
}
max_reach = next_max_reach + 1;
count++;
if (max_reach > query_right) {
break;
}
}
return max_reach > query_right ? count : -1;
};
// Step 3: Process each query and sum up the results
int result_sum = 0;
for (const auto& query : queries) {
int result = min_lamps_needed(query.first, query.second);
if (result != -1) {
result_sum += result;
result_sum %= MOD;
}
}
return result_sum;
}
lightning lamp code , all cases are passing
@allcoding1
👍2
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void dfs(int node, int parent, const vector<vector<int>>& tree, const vector<int>& A, int depth, int& maxDepth) {
maxDepth = max(maxDepth, depth);
for (int child : tree[node]) {
if (child != parent) {
if ((A[node] ^ A[child]) < A[node] && (A[node] ^ A[child]) < A[child]) {
dfs(child, node, tree, A, depth + 1, maxDepth);
}
}
}
}
int main() {
int N;
cin >> N;
vector<int> A(N + 1);
vector<int> P(N + 1);
vector<vector<int>> tree(N + 1);
// Read values array
for (int i = 1; i <= N; ++i) {
cin >> A[i];
}
// Read parent array and buildthe tree
for (int i = 2; i <= N; ++i) { // P[1] is root with P[1] = 0, so start from 2
cin >> P[i];
tree[P[i]].push_back(i);
tree[i].push_back(P[i]);
}
int maxDepth = 0;
dfs(1, 0, tree, A, 1, maxDepth);
cout << maxDepth << endl;
return 0;
}
@allcoding1
#include <vector>
#include <algorithm>
using namespace std;
void dfs(int node, int parent, const vector<vector<int>>& tree, const vector<int>& A, int depth, int& maxDepth) {
maxDepth = max(maxDepth, depth);
for (int child : tree[node]) {
if (child != parent) {
if ((A[node] ^ A[child]) < A[node] && (A[node] ^ A[child]) < A[child]) {
dfs(child, node, tree, A, depth + 1, maxDepth);
}
}
}
}
int main() {
int N;
cin >> N;
vector<int> A(N + 1);
vector<int> P(N + 1);
vector<vector<int>> tree(N + 1);
// Read values array
for (int i = 1; i <= N; ++i) {
cin >> A[i];
}
// Read parent array and buildthe tree
for (int i = 2; i <= N; ++i) { // P[1] is root with P[1] = 0, so start from 2
cin >> P[i];
tree[P[i]].push_back(i);
tree[i].push_back(P[i]);
}
int maxDepth = 0;
dfs(1, 0, tree, A, 1, maxDepth);
cout << maxDepth << endl;
return 0;
}
@allcoding1
👍2
allcoding1
Photo
#include <iostream>
#include <vector>
#include <cmath>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
vector<string> k = {"1234567890", "qwertyuiop", "asdfghjkl", "zxcvbnm"};
string w;
getline(cin, w);
transform(w.begin(), w.end(), w.begin(), ::tolower);
vector<string> words;
string temp;
for (char c : w)
{
if (c == ' ')
{
if (!temp.empty())
{
words.push_back(temp);
temp.clear();
}
}
else
{
temp += c;
}
}
if (!temp.empty())
{
words.push_back(temp);
}
int t = 0;
for (string v : words)
{
int l = v.length();
vector<int> r(l, -1);
vector<int> p(l, -1);
for (int i = 0; i < l; ++i)
{
bool f = false;
for (int j = 0; j < k.size(); ++j)
{
int c = k[j].find(v[i]);
if (c != string::npos)
{
r[i] = j;
p[i] = c;
f = true;
break;
}
}
if (!f)
{
break;
}
}
int c = 0;
for (int i = 1; i < l; ++i)
{
if (r[i] == r[i - 1] && abs(p[i] - p[i - 1]) <= 1)
{
c += 1;
}
else
{
if (c > 0)
{
if (r[i - 1] == -1)
{
t += 2;
}
else
{
t += 1;
}
c = 0;
}
}
}
if (c > 0)
{
if (r[l - 1] == -1)
{
t += 2;
}
else
{
t += 1;
}
}
}
cout << t << endl;
return 0;
}
#include <vector>
#include <cmath>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
vector<string> k = {"1234567890", "qwertyuiop", "asdfghjkl", "zxcvbnm"};
string w;
getline(cin, w);
transform(w.begin(), w.end(), w.begin(), ::tolower);
vector<string> words;
string temp;
for (char c : w)
{
if (c == ' ')
{
if (!temp.empty())
{
words.push_back(temp);
temp.clear();
}
}
else
{
temp += c;
}
}
if (!temp.empty())
{
words.push_back(temp);
}
int t = 0;
for (string v : words)
{
int l = v.length();
vector<int> r(l, -1);
vector<int> p(l, -1);
for (int i = 0; i < l; ++i)
{
bool f = false;
for (int j = 0; j < k.size(); ++j)
{
int c = k[j].find(v[i]);
if (c != string::npos)
{
r[i] = j;
p[i] = c;
f = true;
break;
}
}
if (!f)
{
break;
}
}
int c = 0;
for (int i = 1; i < l; ++i)
{
if (r[i] == r[i - 1] && abs(p[i] - p[i - 1]) <= 1)
{
c += 1;
}
else
{
if (c > 0)
{
if (r[i - 1] == -1)
{
t += 2;
}
else
{
t += 1;
}
c = 0;
}
}
}
if (c > 0)
{
if (r[l - 1] == -1)
{
t += 2;
}
else
{
t += 1;
}
}
}
cout << t << endl;
return 0;
}
👍1
allcoding1
Photo
#include <bits/stdc++.h>
int getMinimumStress(int graph_nodes, int graph_edges, vector<pair<int, int>>& edges, vector<int>& weights, int source, int destination) {
Graph graph(graph_nodes + 1);
for (int i = 0; i < graph_edges; ++i) {
int u = edges[i].first;
int v = edges[i].second;
int w = weights[i];
graph[u].push_back({v, w});
graph[v].push_back({u, w});
}
priority_queue<pii, vector<pii>, greater<pii>> pq;
vector<int> min_stress(graph_nodes + 1, INT_MAX );
pq.push({0, source});
min_stress[source] = 0;
while (!pq.empty()) {
int curr_stress = pq.top().first;
int u = pq.top().second;
pq.pop();
if (u == destination) {
return curr_stress;
}
if (curr_stress > min_stress[u]) {
continue;
}
for (const auto& neighbor : graph[u]) {
int v = neighbor.first;
int weight = neighbor.second;
int next_stress = max(curr_stress, weight);
if (next_stress < min_stress[v]) {
min_stress[v] = next_stress;
pq.push({next_stress, v});
}
}
}
return -1;
}
int getMinimumStress(int graph_nodes, int graph_edges, vector<pair<int, int>>& edges, vector<int>& weights, int source, int destination) {
Graph graph(graph_nodes + 1);
for (int i = 0; i < graph_edges; ++i) {
int u = edges[i].first;
int v = edges[i].second;
int w = weights[i];
graph[u].push_back({v, w});
graph[v].push_back({u, w});
}
priority_queue<pii, vector<pii>, greater<pii>> pq;
vector<int> min_stress(graph_nodes + 1, INT_MAX );
pq.push({0, source});
min_stress[source] = 0;
while (!pq.empty()) {
int curr_stress = pq.top().first;
int u = pq.top().second;
pq.pop();
if (u == destination) {
return curr_stress;
}
if (curr_stress > min_stress[u]) {
continue;
}
for (const auto& neighbor : graph[u]) {
int v = neighbor.first;
int weight = neighbor.second;
int next_stress = max(curr_stress, weight);
if (next_stress < min_stress[v]) {
min_stress[v] = next_stress;
pq.push({next_stress, v});
}
}
}
return -1;
}
👍2
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
double solve(const vector<int>& cnts) {
vector<double> den = {0.20, 0.40, 1, 2, 5, 10};
double tot = 0.0;
for (size_t i = 0; i < cnts.size(); ++i) {
tot += cnts[i] * den[i];
}
return tot;
}
int main() {
vector<int> cnts;
int input;
while (cin >> input) {
cnts.push_back(input);
}
cout << solve(cnts) << endl;
return 0;
}
#include <vector>
#include <numeric>
using namespace std;
double solve(const vector<int>& cnts) {
vector<double> den = {0.20, 0.40, 1, 2, 5, 10};
double tot = 0.0;
for (size_t i = 0; i < cnts.size(); ++i) {
tot += cnts[i] * den[i];
}
return tot;
}
int main() {
vector<int> cnts;
int input;
while (cin >> input) {
cnts.push_back(input);
}
cout << solve(cnts) << endl;
return 0;
}
👍1
#include<stdio.h>
int main() {
int n;
scanf("%d", &n);
char str[n + 1];
scanf("%s", str);
int count = 0;
char thirdLastConsonant;
for(int i = n - 1; i >= 0; i--) {
if (str[i] != 'a' && str[i] != 'e' && str[i] != 'i' && str[i] != 'o' && str[i] != 'u' &&
str[i] != 'A' && str[i] != 'E' && str[i] != 'I' && str[i] != 'O' && str[i] != 'U') {
count++;
if (count == 3) {
thirdLastConsonant = str[i];
break;
}
}
}
printf("%c\n", thirdLastConsonant);
return 0;
}
int main() {
int n;
scanf("%d", &n);
char str[n + 1];
scanf("%s", str);
int count = 0;
char thirdLastConsonant;
for(int i = n - 1; i >= 0; i--) {
if (str[i] != 'a' && str[i] != 'e' && str[i] != 'i' && str[i] != 'o' && str[i] != 'u' &&
str[i] != 'A' && str[i] != 'E' && str[i] != 'I' && str[i] != 'O' && str[i] != 'U') {
count++;
if (count == 3) {
thirdLastConsonant = str[i];
break;
}
}
}
printf("%c\n", thirdLastConsonant);
return 0;
}
👍1🔥1
#include<stdio.h>
int main()
{
int n;
scanf("%d",&n);
int arr[n];
for(int i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
int count=0;
int num=arr[0];
for(int i=1;i<n;i++)
{
if(num!=arr[i])
count++;
}
printf("%d",count);
}
C Language
TCS 1st Qsn
---------------------------------------------------------
N=int(input())
K=int(input())
price=list(map(int,input().split()))
vol=list(map(int,input().split()))
maxvol=0
volu=0
maxvol=max(vol)
for i in range(0,N):
if (maxvol==vol[i] and price[i]<=K):
K=K-price[i]
volu=maxvol
for i in range(0,N):
for j in range(i+1,N+1):
if (price[i]<=K and price[i]==price[j]):
if (vol[i]>vol[j]):
volu=volu+vol[i]
K=K-price[i]
else:
volu=volu+vol[j]
K=K-price[j]
elif (price[i]<=K and price[i]!=price[j]):
K=K-price[i]
-------
include<stdio.h>
int main()
{
int n;
scanf("%d",&n);
int arr[n];
for(int i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
int count=0;
int num=arr[0];
for(int i=1;i<n;i++)
{
if(num!=arr[i])
count++;
}
printf("%d",count);
}
Array Code in C language
int main()
{
int n;
scanf("%d",&n);
int arr[n];
for(int i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
int count=0;
int num=arr[0];
for(int i=1;i<n;i++)
{
if(num!=arr[i])
count++;
}
printf("%d",count);
}
C Language
TCS 1st Qsn
---------------------------------------------------------
N=int(input())
K=int(input())
price=list(map(int,input().split()))
vol=list(map(int,input().split()))
maxvol=0
volu=0
maxvol=max(vol)
for i in range(0,N):
if (maxvol==vol[i] and price[i]<=K):
K=K-price[i]
volu=maxvol
for i in range(0,N):
for j in range(i+1,N+1):
if (price[i]<=K and price[i]==price[j]):
if (vol[i]>vol[j]):
volu=volu+vol[i]
K=K-price[i]
else:
volu=volu+vol[j]
K=K-price[j]
elif (price[i]<=K and price[i]!=price[j]):
K=K-price[i]
-------
include<stdio.h>
int main()
{
int n;
scanf("%d",&n);
int arr[n];
for(int i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
int count=0;
int num=arr[0];
for(int i=1;i<n;i++)
{
if(num!=arr[i])
count++;
}
printf("%d",count);
}
Array Code in C language
👍1
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <cmath>
#include <algorithm>
using namespace std;
struct Line {
int x1, y1, x2, y2;
};
int countCells(Line line, pair<int, int> star, bool split) {
if (line.x1 == line.x2) {
if (split) {
return min(abs(star.second - line.y1), abs(star.second - line.y2)) + 1;
}
else {
return abs(line.y1 - line.y2) + 1;
}
}
else {
if (split) {
return min(abs(star.first - line.x1), abs(star.first - line.x2)) + 1;
}
else {
return abs(line.x1 - line.x2) + 1;
}
}
}
bool intersects(Line a, Line b, pair<int, int>& intersection) {
if (a.x1 == a.x2 && b.y1 == b.y2) {
if (b.x1 <= a.x1 && a.x1 <= b.x2 && a.y1 <= b.y1 && b.y1 <= a.y2) {
intersection = {a.x1, b.y1};
return true;
}
}
if (a.y1 == a.y2 && b.x1 == b.x2) {
if (a.x1 <= b.x1 && b.x1 <= a.x2 && b.y1 <= a.y1 && a.y1 <= b.y2) {
intersection = {b.x1, a.y1};
return true;
}
}
return false;
}
int main() {
int N, K;
cin >> N;
vector<Line> lines(N);
for (int i = 0; i < N; ++i) {
cin >> lines[i].x1 >> lines[i].y1 >> lines[i].x2 >> lines[i].y2;
if (lines[i].x1 > lines[i].x2 || (lines[i].x1 == lines[i].x2 && lines[i].y1 > lines[i].y2)) {
swap(lines[i].x1, lines[i].x2);
swap(lines[i].y1, lines[i].y2);
}
}
cin >> K;
map<pair<int, int>, vector<Line>> stars;
for (int i = 0; i < N; ++i) {
for (int j = i + 1; j < N; ++j) {
pair<int, int> intersection;
if (intersects(lines[i], lines[j], intersection)) {
stars[intersection].push_back(lines[i]);
stars[intersection].push_back(lines[j]);
}
}
}
int asiylam = 0;
for (auto& star : stars) {
if (star.second.size() / 2 == K) {
vector<int> intensities;
for (auto& line : star.second) {
intensities.push_back(countCells(line, star.first, true));
}
asiylam += *min_element(intensities.begin(), intensities.end());
}
}
cout << asiylam << endl;
return 0;
}
Magic Star Intensity Code
C++
TCS Exam
#include <vector>
#include <map>
#include <set>
#include <cmath>
#include <algorithm>
using namespace std;
struct Line {
int x1, y1, x2, y2;
};
int countCells(Line line, pair<int, int> star, bool split) {
if (line.x1 == line.x2) {
if (split) {
return min(abs(star.second - line.y1), abs(star.second - line.y2)) + 1;
}
else {
return abs(line.y1 - line.y2) + 1;
}
}
else {
if (split) {
return min(abs(star.first - line.x1), abs(star.first - line.x2)) + 1;
}
else {
return abs(line.x1 - line.x2) + 1;
}
}
}
bool intersects(Line a, Line b, pair<int, int>& intersection) {
if (a.x1 == a.x2 && b.y1 == b.y2) {
if (b.x1 <= a.x1 && a.x1 <= b.x2 && a.y1 <= b.y1 && b.y1 <= a.y2) {
intersection = {a.x1, b.y1};
return true;
}
}
if (a.y1 == a.y2 && b.x1 == b.x2) {
if (a.x1 <= b.x1 && b.x1 <= a.x2 && b.y1 <= a.y1 && a.y1 <= b.y2) {
intersection = {b.x1, a.y1};
return true;
}
}
return false;
}
int main() {
int N, K;
cin >> N;
vector<Line> lines(N);
for (int i = 0; i < N; ++i) {
cin >> lines[i].x1 >> lines[i].y1 >> lines[i].x2 >> lines[i].y2;
if (lines[i].x1 > lines[i].x2 || (lines[i].x1 == lines[i].x2 && lines[i].y1 > lines[i].y2)) {
swap(lines[i].x1, lines[i].x2);
swap(lines[i].y1, lines[i].y2);
}
}
cin >> K;
map<pair<int, int>, vector<Line>> stars;
for (int i = 0; i < N; ++i) {
for (int j = i + 1; j < N; ++j) {
pair<int, int> intersection;
if (intersects(lines[i], lines[j], intersection)) {
stars[intersection].push_back(lines[i]);
stars[intersection].push_back(lines[j]);
}
}
}
int asiylam = 0;
for (auto& star : stars) {
if (star.second.size() / 2 == K) {
vector<int> intensities;
for (auto& line : star.second) {
intensities.push_back(countCells(line, star.first, true));
}
asiylam += *min_element(intensities.begin(), intensities.end());
}
}
cout << asiylam << endl;
return 0;
}
Magic Star Intensity Code
C++
TCS Exam
👍1
Count press
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
using namespace std;
int dp(string& s, vector<string>& v, unordered_map<string, int>& memo) {
if (memo.count(s)) return memo[s];
int maxRemoval = 0;
for (auto& x : v) {
size_t pos = s.find(x);
if (pos != string::npos) {
string new_string = s.substr(0, pos) + s.substr(pos + x.size());
maxRemoval = max(maxRemoval, 1 + dp(new_string, v, memo));
}
}
return memo[s] = maxRemoval;
}
int main() {
int n;
cin >> n;
vector<string> substrings(n);
for (int i = 0; i < n; ++i) {
cin >> substrings[i];
}
string mainString;
cin >> mainString;
unordered_map<string, int> memo;
cout << dp(mainString, substrings, memo);
return 0;
}
FOLDER AREA
#include <iostream>
#include <cmath>
#include <set>
#include <iomanip>
#include <vector>
#include <utility>
using namespace std;
pair<double, double> reflectPoint(double px, double py, double x1, double y1, double x2, double y2) {
double A = y2 - y1;
double B = x1 - x2;
double C = x2 * y1 - x1 * y2;
double distance = (A * px + B * py + C) / sqrt(A * A + B * B);
double reflectedX = px - 2 * distance * (A / sqrt(A * A + B * B));
double reflectedY = py - 2 * distance * (B / sqrt(A * A + B * B));
return {reflectedX, reflectedY};
}
int main() {
double area;
cout << "Enter area of the square: ";
cin >> area;
double x1, y1, x2, y2;
cout << "Enter the coordinates of the line (x1 y1 x2 y2): ";
cin >> x1 >> y1 >> x2 >> y2;
double side = sqrt(area);
vector<pair<double, double>> corners = {
{0, 0},
{0, side},
{side, side},
{side, 0}
};
set<pair<double, double>> uniquePoints(corners.begin(), corners.end());
for (const auto& corner : corners) {
auto [rx, ry] = reflectPoint(corner.first, corner.second, x1, y1, x2, y2);
uniquePoints.insert({rx, ry});
}
for (const auto& point : uniquePoints) {
cout << fixed << setprecision(2) << point.first << " " << point.second << endl;
}
return 0;
}
Segment display
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<vector<string>> A = {
{"11111", "11111", "11111", "11111", "11111", "11111", "11111", "10001", "11111", "11111", "10001", "10000", "11111", "10001", "01110", "11111", "11111", "11111", "11111", "11111", "10001", "10001", "10001", "10001", "10001", "11111"},
{"10001", "10001", "10000", "10001", "10000", "10000", "10000", "10001", "00100", "00001", "10010", "10000", "10101", "11001", "10001", "10001", "10001", "10001", "10000", "00100", "10001", "10001", "10001", "00000", "10001", "00000"},
{"10001", "10001", "10000", "10001", "10000", "10000", "10000", "10001", "00100", "00001", "10100", "10000", "10101", "10101", "10001", "10001", "10001", "10001", "10000", "00100", "10001", "10001", "10001", "01010", "10001", "00010"},
{"10001", "10001", "10000", "10001", "10000", "10000", "10000", "10001", "00100", "00001", "11000", "10000", "10101", "10011", "10001", "10001", "10001", "10001", "10000", "00100", "10001", "10001", "10001", "00000", "10001", "00000"},
{"11111", "11111", "10000", "10001", "11111", "11111", "10111", "11111", "00100", "10001", "11111", "10000", "10101", "10001", "10001", "11111", "10101", "11111", "11111", "00100", "10001", "10001", "10101", "00100", "11111", "00100"},
{"10001", "10001", "10000", "10001", "10000", "10000", "10001", "10001", "00100", "10001", "10001", "10000", "10001", "10001", "10001", "10000", "10001", "11000", "00001", "00100", "10001", "10001", "10101", "00000", "00001", "00000"},
{"10001", "10001", "10000", "10001", "10000", "10000", "10001", "10001", "00100", "10001", "10001", "10000", "10001", "10001", "10001", "10000", "10011", "10100", "00001", "00100", "10001", "10001", "10101", "01010", "00001", "01000"},
{"10001", "10001", "10000", "10001", "10000", "10000",
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
using namespace std;
int dp(string& s, vector<string>& v, unordered_map<string, int>& memo) {
if (memo.count(s)) return memo[s];
int maxRemoval = 0;
for (auto& x : v) {
size_t pos = s.find(x);
if (pos != string::npos) {
string new_string = s.substr(0, pos) + s.substr(pos + x.size());
maxRemoval = max(maxRemoval, 1 + dp(new_string, v, memo));
}
}
return memo[s] = maxRemoval;
}
int main() {
int n;
cin >> n;
vector<string> substrings(n);
for (int i = 0; i < n; ++i) {
cin >> substrings[i];
}
string mainString;
cin >> mainString;
unordered_map<string, int> memo;
cout << dp(mainString, substrings, memo);
return 0;
}
FOLDER AREA
#include <iostream>
#include <cmath>
#include <set>
#include <iomanip>
#include <vector>
#include <utility>
using namespace std;
pair<double, double> reflectPoint(double px, double py, double x1, double y1, double x2, double y2) {
double A = y2 - y1;
double B = x1 - x2;
double C = x2 * y1 - x1 * y2;
double distance = (A * px + B * py + C) / sqrt(A * A + B * B);
double reflectedX = px - 2 * distance * (A / sqrt(A * A + B * B));
double reflectedY = py - 2 * distance * (B / sqrt(A * A + B * B));
return {reflectedX, reflectedY};
}
int main() {
double area;
cout << "Enter area of the square: ";
cin >> area;
double x1, y1, x2, y2;
cout << "Enter the coordinates of the line (x1 y1 x2 y2): ";
cin >> x1 >> y1 >> x2 >> y2;
double side = sqrt(area);
vector<pair<double, double>> corners = {
{0, 0},
{0, side},
{side, side},
{side, 0}
};
set<pair<double, double>> uniquePoints(corners.begin(), corners.end());
for (const auto& corner : corners) {
auto [rx, ry] = reflectPoint(corner.first, corner.second, x1, y1, x2, y2);
uniquePoints.insert({rx, ry});
}
for (const auto& point : uniquePoints) {
cout << fixed << setprecision(2) << point.first << " " << point.second << endl;
}
return 0;
}
Segment display
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<vector<string>> A = {
{"11111", "11111", "11111", "11111", "11111", "11111", "11111", "10001", "11111", "11111", "10001", "10000", "11111", "10001", "01110", "11111", "11111", "11111", "11111", "11111", "10001", "10001", "10001", "10001", "10001", "11111"},
{"10001", "10001", "10000", "10001", "10000", "10000", "10000", "10001", "00100", "00001", "10010", "10000", "10101", "11001", "10001", "10001", "10001", "10001", "10000", "00100", "10001", "10001", "10001", "00000", "10001", "00000"},
{"10001", "10001", "10000", "10001", "10000", "10000", "10000", "10001", "00100", "00001", "10100", "10000", "10101", "10101", "10001", "10001", "10001", "10001", "10000", "00100", "10001", "10001", "10001", "01010", "10001", "00010"},
{"10001", "10001", "10000", "10001", "10000", "10000", "10000", "10001", "00100", "00001", "11000", "10000", "10101", "10011", "10001", "10001", "10001", "10001", "10000", "00100", "10001", "10001", "10001", "00000", "10001", "00000"},
{"11111", "11111", "10000", "10001", "11111", "11111", "10111", "11111", "00100", "10001", "11111", "10000", "10101", "10001", "10001", "11111", "10101", "11111", "11111", "00100", "10001", "10001", "10101", "00100", "11111", "00100"},
{"10001", "10001", "10000", "10001", "10000", "10000", "10001", "10001", "00100", "10001", "10001", "10000", "10001", "10001", "10001", "10000", "10001", "11000", "00001", "00100", "10001", "10001", "10101", "00000", "00001", "00000"},
{"10001", "10001", "10000", "10001", "10000", "10000", "10001", "10001", "00100", "10001", "10001", "10000", "10001", "10001", "10001", "10000", "10011", "10100", "00001", "00100", "10001", "10001", "10101", "01010", "00001", "01000"},
{"10001", "10001", "10000", "10001", "10000", "10000",
👍3
target_idx += 1
sub_idx += 1
total_deletions = len(sub_str) - match_length
return match_length, total_deletions
def process_input():
inp = sys.stdin.read().splitlines()
pos = 0
num_strings = int(inp[pos].strip())
pos += 1
Office rostering code
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
int main() {
int n, m, k, days = 1, activeCount = 0;
cin >> n >> m;
vector<set<int>> connections(n);
for (int i = 0, u, v; i < m; ++i) {
cin >> u >> v;
connections[u].insert(v);
connections[v].insert(u);
}
cin >> k;
vector<bool> active(n, true);
activeCount = n;
while (activeCount < k) {
vector<bool> nextState(n, false);
for (int i = 0; i < n; ++i) {
int neighborCount = 0;
for (int neighbor : connections[i]) {
neighborCount += active[neighbor];
}
if (active[i] && neighborCount == 3) {
nextState[i] = true;
} else if (!active[i] && neighborCount < 3) {
nextState[i] = true;
}
}
active = nextState;
activeCount += count(active.begin(), active.end(), true);
++days;
}
cout << days;
return 0;
}
BUZZ DAY SALE
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> ids(n), costs(n);
for (int i = 0; i < n; i++) cin >> ids[i];
for (int i = 0; i < n; i++) cin >> costs[i];
int budget;
cin >> budget;
int maxItems = 0, minCost = 0;
for (int i = 0; i < n; i++) {
int itemCost = costs[i];
int quantity = budget / itemCost;
if (quantity > 0) {
int currentItems = 0, currentCost = 0;
for (int j = 0; j < n; j++) {
if (i != j && ids[i] % ids[j] == 0) {
currentItems += quantity;
currentCost += costs[j] * quantity;
}
}
if (currentItems > maxItems || (currentItems == maxItems && currentCost > minCost)) {
maxItems = currentItems;
minCost = currentCost;
}
}
}
cout << maxItems << " " << minCost << endl;
return 0;
}
Arrange map code
from collections import deque
import itertools
def shortest_path(grid, n):
start, end = None, None
for i in range(n):
for j in range(n):
if grid[i][j] == 'S':
start = (i, j)
elif grid[i][j] == 'D':
end = (i, j)
queue = deque([(start, 0)])
visited = {start}
while queue:
(x, y), distance = queue.popleft()
if (x, y) == end:
return distance
for nx, ny in [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]:
if 0 <= nx < n and 0 <= ny < n and (nx, ny) not in visited and grid[nx][ny] != 'T':
visited.add((nx, ny))
queue.append(((nx, ny), distance + 1))
return float('inf')
def split_grid(grid, size, block):
sections = []
for i in range(0, size, block):
for j in range(0, size, block):
block_section = [grid[x][j:j+block] for x in range(i, i+block)]
sections.append(block_section)
return sections
def rebuild_grid(order, sections, size, block):
full_grid = [["" for _ in range(size)] for _ in range(size)]
num_blocks = size // block
for index, section_index in enumerate(order):
section = sections[section_index]
row_offset = (index // num_blocks) * block
col_offset = (index % num_blocks) * block
for i in range(block):
for j in range(block):
full_grid[row_offset + i][col_offset + j] = section[i][j]
return full_grid
def main():
size, block_size = map(int, input().split())
original_grid = [list(input().strip()) for _ in range(size)]
sections = split_grid(original_grid, size, block_size)
total_sections = (size // block_size
sub_idx += 1
total_deletions = len(sub_str) - match_length
return match_length, total_deletions
def process_input():
inp = sys.stdin.read().splitlines()
pos = 0
num_strings = int(inp[pos].strip())
pos += 1
Office rostering code
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
int main() {
int n, m, k, days = 1, activeCount = 0;
cin >> n >> m;
vector<set<int>> connections(n);
for (int i = 0, u, v; i < m; ++i) {
cin >> u >> v;
connections[u].insert(v);
connections[v].insert(u);
}
cin >> k;
vector<bool> active(n, true);
activeCount = n;
while (activeCount < k) {
vector<bool> nextState(n, false);
for (int i = 0; i < n; ++i) {
int neighborCount = 0;
for (int neighbor : connections[i]) {
neighborCount += active[neighbor];
}
if (active[i] && neighborCount == 3) {
nextState[i] = true;
} else if (!active[i] && neighborCount < 3) {
nextState[i] = true;
}
}
active = nextState;
activeCount += count(active.begin(), active.end(), true);
++days;
}
cout << days;
return 0;
}
BUZZ DAY SALE
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> ids(n), costs(n);
for (int i = 0; i < n; i++) cin >> ids[i];
for (int i = 0; i < n; i++) cin >> costs[i];
int budget;
cin >> budget;
int maxItems = 0, minCost = 0;
for (int i = 0; i < n; i++) {
int itemCost = costs[i];
int quantity = budget / itemCost;
if (quantity > 0) {
int currentItems = 0, currentCost = 0;
for (int j = 0; j < n; j++) {
if (i != j && ids[i] % ids[j] == 0) {
currentItems += quantity;
currentCost += costs[j] * quantity;
}
}
if (currentItems > maxItems || (currentItems == maxItems && currentCost > minCost)) {
maxItems = currentItems;
minCost = currentCost;
}
}
}
cout << maxItems << " " << minCost << endl;
return 0;
}
Arrange map code
from collections import deque
import itertools
def shortest_path(grid, n):
start, end = None, None
for i in range(n):
for j in range(n):
if grid[i][j] == 'S':
start = (i, j)
elif grid[i][j] == 'D':
end = (i, j)
queue = deque([(start, 0)])
visited = {start}
while queue:
(x, y), distance = queue.popleft()
if (x, y) == end:
return distance
for nx, ny in [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]:
if 0 <= nx < n and 0 <= ny < n and (nx, ny) not in visited and grid[nx][ny] != 'T':
visited.add((nx, ny))
queue.append(((nx, ny), distance + 1))
return float('inf')
def split_grid(grid, size, block):
sections = []
for i in range(0, size, block):
for j in range(0, size, block):
block_section = [grid[x][j:j+block] for x in range(i, i+block)]
sections.append(block_section)
return sections
def rebuild_grid(order, sections, size, block):
full_grid = [["" for _ in range(size)] for _ in range(size)]
num_blocks = size // block
for index, section_index in enumerate(order):
section = sections[section_index]
row_offset = (index // num_blocks) * block
col_offset = (index % num_blocks) * block
for i in range(block):
for j in range(block):
full_grid[row_offset + i][col_offset + j] = section[i][j]
return full_grid
def main():
size, block_size = map(int, input().split())
original_grid = [list(input().strip()) for _ in range(size)]
sections = split_grid(original_grid, size, block_size)
total_sections = (size // block_size
👍2