[Sorting written test preparation]

tags: C++  algorithm  Data structure  

Written questions (experience in the written test, re -organize here)

1. Q: There are n seats (1-n) for numbers to give M rules. One of the rules is to sit at most X from position L to position R.

How many passengers do you sit at most?

enter:
Input n, m, m,
Then enter three numbers in M ​​line, representing L, R, x

Code:

#include <iostream>
#include<vector>
#include<stack>
#include<algorithm>
#include<string>
#include<unordered_set>
using namespace std;

int main()
{
         // input
	int n, m;
	cin >> n >> m;
	vector<vector<int>> regular;
	for (int i = 0; i < m; i++)
	{
		vector<int> new_line;
		for (int j = 0; j < 3; j++)
		{
			int temp;
			cin >> temp;
			new_line.push_back(temp);
		}
		regular.push_back(new_line);
	}
         // Sort the interval first, and sort according to the starting position of the interval.
	sort(regular.begin(), regular.end(), [](vector<int> a, vector<int> b) {return a[0] < b[0]; });
	
	 int Sum = 0; // Record the number of passengers
	 int Start = -1, END = -1, Value = 0; // Used to record the intersection interval for integrated interval and maximum ride number
	 int p = 0; // Used for traversal intervals
	
	while (p < m)
	{
		 if (Start == -1 && END == -1) // The first range and the front seat
		{
		     // Update range Start
			start = regular[p][0];
			end = regular[p][1];
			value = regular[p][2];

			 SUM += Start -1; // Record the seat in front of the first interval
			 p ++; // Find the next range directly
		}
                 // The start of the second interval is less than the end of the previous interval, indicating that the intersection of the two interval
		 if (regular [p] [0] <= end) // intersect
		{
		     // The intersection is divided into overlap and non -heavy
			 if (regular [p] [1]> end)
			{
			     // Need to end the update range and up to the maximum number of rides
				end = regular[p][1];
				value += regular[p][2];

				if (value > end - start + 1)
				{
					value = end - start + 1;
				}
			}
			 // Note: Re -coexisting means that the number of rides in the current interval must be included in the number of rides in the recorded interval, and because the number of rides in the current interval must be less than the number of rides in the interval of the record, the value does not change unchanged.
			 // I did not consider this during the written test, and directly added the number of rides between the two intervals. Essence Essence Essence Essence Essence Essence 
			
		}
		 else // Never intersect
		{
			sum += value;
			sum += regular[p][0] - end - 1;
			start = regular[p][0];
			end = regular[p][1];
			value = regular[p][2];
		}
		p++;
	}

	 // The last one and the end of the end
	sum += value;
	sum += n-end;

	cout << sum;
	return 0;

}

2. Q: Xiao Hong got an array A. Each time Xiao Hong could choose any number in the array, minus X, and Xiaohong operated a total of K times. The maximum value of the array is as small as possible, and the maximum value is returned.

example:
4 3 11 2 1
3

Code:

#include <iostream>
#include<vector>
#include<stack>
#include<algorithm>
#include<string>
#include<unordered_set>
using namespace std;

 // Initialize a certain position in the pile
void init_heap(vector<int>& a,int position,int n)
 {// pose: To update position n: The length of the heap
	
	while (1)
	{
		int i = position;
		if (2 * position <= n&&a[position] < a[position * 2]) i = position * 2;
		if(2 * position +1 <= n&&a[i] < a[position * 2+1]) i = position * 2+1;
		if (position == i) break;
		swap(a[position],a[i]);
	}
	
}

int main()
{
	int n, k, x;
	cin >> n >> k >> x;
	vector<int> a;
	for (int i = 0; i < n; i++)
	{
		int temp;
		cin >> temp;
		a.push_back(temp);
	}
	 	//calculate 
	 // sort
	 /*During the written test, this method is out of time, similar to inserting sorting, and find the maximum value of the array at a time
	sort(a.begin(), a.end());
	for (int i = 0; i < k; i++)
	{
		a[n - 1] -= x;
		for (int j = n - 2; j >= 0 && a[j] > a[j + 1]; j--)
		{
			swap(a[j], a[j + 1]);
		}
	}
	cout << a[n - 1];
*/
 // After query stack sorting, it seems that it is no longer overtime
 for (int i = n/2; i> 0; i-) // Initialized heap sorting
	{
		init_heap(b, i, n);
	}
	 For (int i = 0; I <k; I ++) // Settle X at a time and update the pile top
	{
		b[1] -= x;
		init_heap(b, 1, n);
	}
	 core << b [1]; // Output the top value, the maximum value
	
	return 0;
}

3. Xiaomi written test, when doing this question, only Java has templates, C ++ has no templates, and I have been old for a long time.

Give a binary tree, how to make a two -way linked list, and output it from left to right from right to right
example:
1
2 3
4 5 6 7
Two -way linked list: 4 5 2 1 6 3 7

Traversing: 45216377361254

import java.io.*;
import java.util.*;
import java.util.Stack;
import java.text.*;
import java.math.*;
import java.util.regex.*;


class Node {
	public int data;
	public Node left;
	public Node right;

	public Node(int data) {
		this.data = data;
	}

	public Node() {
	}

	public Node(int data, Node left, Node right) {
		this.data = data;
		this.left = left;
		this.right = right;
	}
}

class Solution {

	/* Write Code Here */
	public void BFS(Node pRootOfTree, Stack<Node> s)
	{
		if (pRootOfTree == null) return;

		BFS(pRootOfTree.left, s);
		s.push(pRootOfTree);
		BFS(pRootOfTree.right, s);

	}
	public Node  Convert(Node pRootOfTree) {
		Node pre = null;
		Stack<Node> s = new Stack<Node>();
		BFS(pRootOfTree, s);
		while (!s.empty())
		{
			Node temp = s.peek();
			s.pop();
			if (pre == null)
			{
				pre = temp;
				pre.left = null;
				pre.right = null;
			}
			else
			{
				pre.left = temp;
				temp.right = pre;
				pre = temp;
				pre.left = null;
			}
		}


		return pre;
	}
}

public class Main {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		Node res = null;
		List<Node> list = new ArrayList<>();

		while (in.hasNext()) {
			int item = in.nextInt();
			if (item == -1) {
				list.add(null);
			}
			else {
				list.add(new Node(item));
			}
		}
		int len = list.size();
		int i = 0;
		while (i <= (len - 2) / 2) {
			if (2 * i + 1 < len && list.get(i) != null) {
				list.get(i).left = list.get(2 * i + 1);
			}
			if (2 * i + 2 < len && list.get(i) != null) {
				list.get(i).right = list.get(2 * i + 2);
			}
			i++;
		}

		res = new Solution().Convert(list.get(0));
		if (res != null) {
			while (res.right != null && res.data != -1) {
				System.out.print(String.valueOf(res.data) + " ");
				res = res.right;
			}
			System.out.print(res.data + " ");
			while (res.left != null && res.data != -1) {
				System.out.print(String.valueOf(res.data) + " ");
				res = res.left;
			}
			System.out.print(res.data);
		}
		System.out.println();
	}
}

4. Xiaomi written test: very simple, but record it

A section of the linked list in the middle of the linked list
1 2 3 4 5
Reversal: 2-4
Result: 1 4 3 2 5
Code:

#include <iostream>
#include <vector>
#include <numeric>
#include <limits>
#include <stack>

using namespace std;

template <class Type> class ListNode {
public:
	Type data;
	ListNode<Type> *next;
};

class Solution {
public:

	/* Write Code Here */
	ListNode < int > *reverseBetween(ListNode<int> *head, int left, int right) {
		ListNode<int> *last = nullptr, *pre = head;
		for (int i = 0; i < left - 1; i++)
		{
			last = pre;
			pre = pre->next;
		}
		stack<ListNode<int>*> s;
		for (int i = 0; i < right - left + 1; i++)
		{
			s.push(pre);
			pre = pre->next;
		}

		 // Out of the stack reversing linked list
		while (!s.empty())
		{
			ListNode<int> *temp = s.top();
			s.pop();
			if (last == nullptr)
			{
				last = temp;
			}
			else
			{
				last->next = temp;
				last = temp;
			}
			
		}
		last->next = pre;
		return head;

	}
};
int main() {
	ListNode < int > *res = NULL;

	int head_size = 0;
	cin >> head_size;

	ListNode<int> *head = NULL, *head_curr = NULL;
	int head_item;
	for (int head_i = 0; head_i < head_size; head_i++) {
		cin >> head_item;

		ListNode<int> *head_temp = new ListNode<int>();
		head_temp->data = head_item;
		head_temp->next = NULL;
		if (head == NULL) {
			head = head_curr = head_temp;
		}
		else {
			head_curr->next = head_temp;
			head_curr = head_temp;
		}
	}

	int left;
	cin >> left;



	int right;
	cin >> right;



	Solution *s = new Solution();
	res = s->reverseBetween(head, left, right);
	while (res != NULL) {
		cout << res->data << " ";
		res = res->next;
	}
	cout << endl;

	return 0;

}

5. Written test (Forgot which company): The maximum sum of the two non -overlapping sub -arrays

Example:
Enter: [-3,1,2,3, -1,2,8,0, -1, -6,9,2]
Output: 26
[1,2,3, -1,2,8] and [9,2]
There is the following derivation and extension

1. The maximum subsequent sequence in the array
In this issue, there is a linear dynamic solution
Starting from position 0 to position n, the largest sub -sequence is [ai, a (i+1) ... a (i+x)]
Every time I find this position, determine whether the position of the position and the previous position is greater than 0, so that the position is equal to the
Of course, after each position is required, it is necessary to judge which one is larger than the maximum value of the front position.
Code:

int getMaxOneArraySum(vector<int>& vec)
{
	// Full version
	int n = vec.size();
	int max_num = INT_MIN;
	vector<int> dp(n,0);
	dp[0] = max(vec[0], 0);
	for (int i = 1; i < n; i++)
	{
	 // If the sum of the DP and the number of current positions in the previous position is less than 0, then it means that the continuous sequence is interrupted, the DP update is 0, and the DP is updated to
		dp[i] = max(dp[i-1] + vec[i], 0);
	}
	 // Find the maximum value in all subsequent sequences
	for (int i = 0; i < n; i++)
	{
		if (dp[i] > max_num)
		{
			max_num = dp[i];
		}
	}
	return max_num;

	 // The optimized version does not require all records, only the largest subsequent subsequent subsequent sub -sequence and
	/*int n = vec.size();
	int max_num = INT_MIN;
	int dp = 0;
	for (int i = 0; i < n; i++)
	{
		dp = max(dp + vec[i], 0);
		max_num = max(dp, max_num);
	}
	return max_num;*/
}

2. The maximum sum of the two array sequences of the two arrays
In the previous problem, we can find that the maximum value of the prefix dp_left contains the prefix from left to right.
Then if we traverse from right to left, we can find the maximum and DP_RIGHT containing the suffix in this position
Then we can get two dynamic array, the maximum sequence distribution in the opposite direction
Because the two non -overlapping sequences must be one on the left, one on the right, may be connected, or it may not be connected.
DP_LeFT [i] represents the maximum sequence between 0 –i and DP_Right [i] on the largest sequence and
Then we can find the maximum value of dp_left [i]+dp_richt [i+1] according to the dynamic array we are looking for
Before calculating, you need to traverse two dynamic array, and modify the DP [i] to the largest sequence between 0-i, that is,:

// dp [n] dp [i] The value of 0-I is the maximum sub-sequence and
for(int i=1;i<n;i++)
{
	dp[i]=max(dp[i],dp[i-1]);
}

The final code:

int getMaxTwoArraySum(vector<int>& vec)
{
	int length = vec.size();
	vector<int> dp(vec.size(), 0);
	vector<int> dp_inverse(vec.size(),0);

	 // Construct DP array
	dp[0] = vec[0];
	dp_inverse[length - 1] = vec[length - 1];
	for (int i = 1; i < length; i++)
	{
		if (dp[i - 1] > 0)
		{
			dp[i] = dp[i - 1] + vec[i];
		}
		else
		{
			dp[i] = vec[i];
		}
		if (dp_inverse[length - i] > 0)
		{
			dp_inverse[length - i - 1] = dp_inverse[length - i] + vec[length - i - 1];
		}
		else
		{
			dp_inverse[length - i - 1] = vec[length - i - 1];
		}
	}
	 // Print positive DP array
	for (int i = 0; i < length; i++)
	{
		cout << dp[i] << " ";
	}
	cout << endl;

	 // Print the reverse DP array
	for (int i = 0; i < length; i++)
	{
		cout << dp_inverse[i] << " ";
	}
	cout << endl;

	 // Replace the value of the DP array to start from left (right) to start with the largest sub -array length of the current position
	for (int i = 1; i < length; i++)
	{
		dp[i] = max(dp[i], dp[i - 1]);
		dp_inverse[length - i - 1] = max(dp_inverse[length - i], dp_inverse[length - i - 1]);
	}

	 // Print positive DP array
	for (int i = 0; i < length; i++)
	{
		cout << dp[i] << " ";
	}
	cout << endl;

	 // Print the reverse DP array
	for (int i = 0; i < length; i++)
	{
		cout << dp_inverse[i] << " ";
	}
	cout << endl;

	 // Find out the two largest sub -sequences of the left and right array combinations
	int max_sum = 0;
	for (int i = 0; i < length - 1; i++)
	{
		int sum = dp[i] + dp_inverse[i + 1];
		max_sum = max(max_sum, sum);
	}
	return max_sum;
}

3. The maximum sequence of the ring array

In 1, we look for the largest sequence of the non -loop arrays. On this issue, we need to consider the problem of connected head and tail.
Solution: We can find the maximum sum of the continuous sequence, which means that we can find the minimum of the continuous sequence. And the sum of the entire array minimum value, you can get the maximum value connected to the end and end
Code:

// The largest sequence in the cycle array and
int getMaxOneCricleArraySum(vector<int>& vec)
{
	int n = vec.size();
	int dp = 0, max_num = INT_MIN;
	for (int i = 0; i < n; i++)
	{
		dp = max(dp + vec[i], 0);
		max_num = max(dp, max_num);
	}

	int dp_min = 0, min_num = INT_MAX;
	int sum = 0;
	 // Find the minimum value
	for (int i = 0; i < n; i++)
	{
		sum += vec[i];
		dp_min = min(dp_min + vec[i], 0);
		min_num = min(dp_min, min_num);
	}
	cout << max_num << " " << sum - min_num << endl;
	return max(max_num, sum - min_num);

}

4. Two non -overlapping sequences of the ring array maximum sum
This problem can be divided into two cases:
When two sequences are different, it contains the first and tails: in this case, just find the two largest sequences in the array according to the 2 in the 2 in this case.
The other is that one sequence contains the first tail and the other is not connected. In this case, find out the maximum sequence in the ring array in the reference 3. Just find the two minimum sequences in the sequence. The sum of the two minimum minimum sequences with the total of the elements in the array is the two largest sequences.
Just find out the biggest sequence and comparison in these two cases.
Code:

// Two sections in the ring array do not overlap the maximum sequence and
int getMaxTwoCircleArraySum(vector<int>& vec)
{
	int n = vec.size();
	 // 1, the first tail is not connected
	 vector <int> dp0 (n, 0), dp1 (n, 0); // positive and reverse
	dp0[0] = max(vec[0], 0);
	dp1[n - 1] = max(vec[n - 1], 0);
	for (int i = 1; i < n; i++)
	{
		dp0[i] = max(dp0[i] + vec[i], 0);
	}
	for (int i = n - 2; i >= 0; i--)
	{
		dp1[i] = max(dp1[i + 1] + vec[i], 0);
	}

	 // Set the maximum sequence and
	for (int i = 1; i < n; i++)
	{
		dp0[i] = max(dp0[i - 1], dp0[i]);
	}
	for (int i = n - 2; i >= 0; i--)
	{
		dp1[i] = max(dp1[i + 1], dp1[i]);
	}

	int max0 = 0;
	for (int i = 1; i < n; i++)
	{
		max0 = max(max0, dp0[i - 1] + dp1[i]);
	}

	 // 2. Connect the first and tail (find two minimum sequences and)
	vector<int> dp2(n), dp3(n);
	dp2[0] = min(vec[0], 0);
	dp3[n - 1] = min(vec[n - 1], 0);
	for (int i = 1; i < n; i++)
	{
		dp2[i] = min(dp2[i - 1] + vec[i], 0);
	}
	for (int i = n - 2; i >= 0; i--)
	{
		dp3[i] = min(dp3[i + 1] + vec[i], 0);
	}
	 // Set the minimum prefix in the current direction position
	for (int i = 1; i < n; i++)
	{
		dp2[i] = min(dp2[i], dp2[i - 1]);
	}
	for (int i = n - 2; i >= 0; i--)
	{
		dp3[i] = min(dp3[i],dp3[i + 1]);
	}
	int min0 = 0;
	for (int i = 1; i < n; i++)
	{
		min0 = min(min0, dp2[i - 1] + dp3[i]);
	}
	int sum = 0;
	for (int i = 0; i < n; i++)
	{
		sum += vec[i];
	}
	return max(max0, sum - min0);

}

Test code:

int main()
{
	vector<int> vec = { -3,1,2,3,-1,2,8,0,-1,-6,9,2 };
	//cout << getMaxTwoArraySum(vec) << endl;
	//cout << getMaxOneArraySum(vec) << endl;
	//cout << getMaxOneCricleArraySum(vec) << endl;
	cout << getMaxTwoCircleArraySum(vec) << endl;
	return 0;
}

5. The largest sub -array of the product
Give you an integer array Nums, please find out the non -empty continuity array with the largest product in the array (at least one number in the sub -array) and return the product of the sub -array
Enter: 2, 3, -2, 4
Output: 6

The solution method is more interesting, while maintaining the maximum and minimum values. When the number of less than 0 is encountered, the maximum and minimum value of the exchange is used to multiply with this value to save the maximum value and minimum value, respectively. And update the maximum value in the record process.

 int maxProduct(vector<int>& nums) {
        int ans=INT_MIN,imax=1,imin=1;
        for(int i=0;i<nums.size();i++)
        {
            if(nums[i]<0)
            {
                int temp=imax;
                imax=imin;
                imin=temp;
            }
            imax=max(imax*nums[i],nums[i]);
            imin=min(imin*nums[i],nums[i]);
            ans=max(imax,ans);
        }
        return ans;
    }

Enter: 2, 3, -2, 4
imax: 2, 6 , 1, 4
imin: 1 , 1 , -12, -48
ans: 2 , 6 , 6, 6

Input: -2 0 -1
imax: -2 0 0
imin: -2 0 -1
ans: -2 0 0

Input: 0 -2 -3
imax: 0 0 6
imin: 0 -2 0
ans: 0 0 6

There will be no errors in the middle, there will be no errors

6. Sort the same strange couples adjacent to a string to get the maximum value

Example: Input: 0082663
Output: 8662003


 // Sort in continuous odd counts in a string
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

string GetLargestNumber(string num)
{
	 // Convert to int
	int n = num.size();
	vector<int> num_int(n);
	for (int i = 0; i < n; i++)
	{
		num_int[i] = num[i] - '0';
	}
	 // Find a continuous odd number even
	 int FLAG = 0; // 0 represents the even number
	if (num_int[0] % 2 == 0)
	{
		flag = 0;
	}
	else
	{
		flag = 1;
	}
	int start = 0;
	for (int i = 1; i < n; i++)
	{
		if (num_int[i] % 2 != flag)
		{
			sort(num_int.begin() + start, num_int.begin() + i, [](int a, int b) {return a > b; });
			flag = num_int[i] % 2;
			start = i;
		}
	}
	sort(num_int.begin() + start, num_int.end(), [](int a, int b) {return a > b; });

	 // Convert to a string
	string ans;
	for (int i = 0; i < n; i++)
	{
		ans.push_back(num_int[i] + '0');
	}
	return ans;
}

int main()
{
	string s = "0082663";
	cout<<GetLargestNumber(s);
}

7. The number of sequences that contain the longest continuous 1 (convinced the third programming)

A 01 string of length n, find the number of sub -string containing the longest continuous 1 sub -string
Example: Input: 0110
Output: 4 (0110, 011, 110, 11)

First look at the code made during a written test, and use the idea of ​​deep priority search, or the idea of ​​recursive, traversing the possibility of all string, and saved it in the set collection. Failure
Code:

#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;

void BFS(string& arr, int start, int end, unordered_set<string>& ans)
{
	if (start >= 0 && end < arr.size())
	{
		string temp = arr.substr(start, end - start);
		if (ans.count(temp) == 0)
		{
			ans.emplace(temp);
		}
		 // to the left to right
		BFS(arr, start - 1, end, ans);
		BFS(arr, start, end + 1, ans);
	}
}
int main() {
	int n;
	cin >> n;
	string arr;
	cin >> arr;
	 	//calculate 
	int l = 0, r = 0, start = 0, end = 0;

	while (r < n)
	{
		if (arr[r] == '1')
		{
			r++;
		}
		else
		{
			if (l == r)
			{
				l++;
				r++;
			}
			else
			{
				if (r - l > end - start + 1)
				{
					start = l;
					end = r - 1;
				}
				r++;
				l = r;
			}
		}
	}

	if (l != r)
	{
		if (r - l > end - start + 1)
		{
			start = l;
			end = r - 1;
		}
	}
	unordered_set<string> ans;
	BFS(arr, start, end, ans);
	cout << ans.size() % 1000000007;
	return 0;
}

There is only one possibility that you should need to use dynamic planning! Intersection Intersection
I ca n’t think of it, Damn, I really enter the interview, I must ask! Intersection Intersection

8. Create a picture of the shortest path (byte first programming)

enter:
Node N
Array A [n]
A [i] represents the distance from nodes 1 to node I+1 (the description in the actual topic is completely wrong, is this a large factory?)
Create a picture that conforms to the description of the appeal

Idea: Each position in each array A is reduced by one, which is equal to the connection to 0 in the previous time.

#include <iostream>
#include <vector>
#include <queue>
using namespace std;

int main() {
	 int n; // Node number
	cin >> n;
	vector<int> a(n);
	for (int i = 0; i < n; i++)
	{
		cin >> a[i];
	}

	 	//calculate 
	vector<vector<int>> ans;

	int start = 1;
	int flag = -1;
	while (flag == -1)
	{
		queue<int> t;
		for (int i = 0; i < n; i++)
		{

			a[i]--;
			if (a[i] == 0)
			{
				t.push(i + 1);
			}
		}
		if (t.size() == 0)
		{
			flag = 1;
		}
		else
		{
			int num = -1;
			while (!t.empty())
			{
				num = t.front();
				t.pop();
				vector<int> temp = { start,num };
				ans.push_back(temp);
			}
			start = num;
		}
	}

	if (ans.size() != n - 1)
	{
		cout << -1;
	}
	else
	{
		cout << ans.size() << endl;
		for (int i = 0; i < ans.size(); i++)
		{
			cout << ans[i][0] << " " << ans[i][1] << endl;
		}
	}


	return 0;

}

9. Tree node dyeing (byte second programming)

The start of a tree node is all red, dyeing blue nodes, as many blue nodes as possible, and the number of blue nodes of the subtree is strange
Note: Node No. 1 is the root node (big pit)
Input: Number of Nodes: N
N-1 line: x y explains that there is a connection between x and y

The example is given the example. The sequence number is small on it, but when saved and submitted, the information in this example is wrong, but it is okay.

Idea:
Adopting recursive methods, it can also be said to be a post -sequential traversal
After the left and right sub -trees are operated, operate on the root node
Determine the color of the root node according to the number of blue nodes and the strangeness of the left and right sub -tree blue nodes, and return the number of blue nodes


 // Blue Strange Tree

#include <iostream>
#include <vector>
using namespace std;

int BFS(vector<vector<int>> &tree, int i, int j, vector<int> &c, vector<int> &flag)
{
	flag[tree[i][j]] = 1;
	int node = tree[i][j];
	int num = 0;
	for (int z = 0; z < tree[node].size(); z++)
	{
		if (flag[tree[node][z]] == 0)
		{
			num += BFS(tree, node, z, c, flag);
		}
	}
	if (num % 2 == 0)
	{
		c[tree[i][j]] = 1;
		return num + 1;
	}
	else
	{
		return num;
	}
}


int main() {
	int n;
	cin >> n;
	vector<int> c(n + 1, 0);
	vector<int> flag(n + 1, 0);
	vector<vector<int>> tree(n + 1);
	for (int i = 0; i < n - 1; i++)
	{
		int x, y;
		cin >> x >> y;
		tree[x].push_back(y);
		tree[y].push_back(x);
		 // The sample information error in the written test, add the FLAG array to record whether the corresponding node has traversed
		//         if(x<y)
		//         {
		//             tree[x].push_back(y);
		//         }
		//         else
		//         {
		//             tree[y].push_back(x);
		//         }
	}
	 	//calculate 
	 // Use recursively
	tree[0].push_back(1);
	BFS(tree, 0, 0, c, flag);

	for (int i = 1; i <= n; i++)
	{
		if (c[i] == 1)
		{
			cout << "B";
		}
		else
		{
			cout << "R";
		}
	}

	return 0;

}

10 The matching quantity of the same subset and harmony (the third program programming)

The pony gets an array, some of which are dyed red, and some are dyed in blue
Select the subsets of two colors, which requires red and purple subsets as the same

Input: Array Size N
Array A [n]
String s [n] RBRB corresponding character represents the color of the corresponding position number

Idea:
1. First divide the array A into two camps according to the color
Using recucted ideas, find out all the combinations of all the combinations of the two camps and find out the full arrangement of ideas.
However, the recursive timeout is over, and only 40%of the completion is 1001ms. Essence Essence

2. Therefore, on this basis, first merge the same number in the same camp and record the number of the same number
When recursively, add the number of the number directly, but the result is wrong
It seems that if you understand that there are three in the same camp in the number 2, if one has been used in the combination, then there are only two possibilities for the next 2 o'clock. Essence Essence I really have the wrong thinking

Attach two methods here:
Method 1:


#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;

void BFS(vector<int> &r, int x, unordered_map<int, int> &map1, int sum)
{
	for (int i = x; i < r.size(); i++)
	{
		sum += r[i];
		map1[sum]++;
		BFS(r, i + 1, map1, sum);
		sum -= r[i];
	}
}



int main() {
	int n;
	cin >> n;
	vector<int> a(n);
	for (int i = 0; i < n; i++)
	{
		cin >> a[i];
	}
	string c;
	cin >> c;

	 	//calculate 
	 	//separate 
	vector<int> r, b;
	for (int i = 0; i < n; i++)
	{
		if (c[i] == 'R')
		{
			r.push_back(a[i]);
		}
		else
		{
			b.push_back(a[i]);
		}
	}

	 // Calculate the recursion method
	unordered_map<int, int> map1, map2;
	int sum1 = 0, sum2 = 0;
	BFS(r, 0, map1, sum1);
	BFS(b, 0, map2, sum2);
	int ans = 0;
	for (auto item : map1)
	{
		if (map2[item.first] != 0)
		{
			ans += item.second*map2[item.first];
		}

	}
	cout << ans;

	return 0;
}

Method 2:

#include <iostream>
#include <vector>
#include <unordered_map>
#include <string>
using namespace std;

void BFS(vector<int> &r, int x, unordered_map<int, int> &map1, int sum, unordered_map<int, int> &r1, int time)
{
	for (int i = x; i < r.size(); i++)
	{
		 int T = Time; // The number of combinations last time
		 t *= r1 [r [i]]; // The number of combinations of the last time is multiplied with the number of positions in the position, which is the possibility of total
		 SUM += R [i]; // Total harmony
		 map1 [sum] += t; // Directly add the number of combinations corresponding to the SUM
		 BFS (R, I + 1, MAP1, SUM, R1, T); // Add the next number
		 SUM -= r [i]; // Delete the number of this position, change the number
	}
}



int main() {
	int n;
	cin >> n;
	vector<int> a(n);
	for (int i = 0; i < n; i++)
	{
		cin >> a[i];
	}
	string c;
	cin >> c;

	 	//calculate 
	 	//separate 
	vector<int> r, b;
	unordered_map<int, int> r1, b1;
	for (int i = 0; i < n; i++)
	{
		if (c[i] == 'R')
		{
			if (r1.count(a[i]) == 0)
			{
				r.push_back(a[i]);
			}
			r1[a[i]]++;
		}
		else
		{
			if (b1.count(a[i]) == 0)
			{
				b.push_back(a[i]);
			}
			b1[a[i]]++;
		}
	}

	 // Calculate the recursion method
	unordered_map<int, int> map1, map2;
	int sum1 = 0, sum2 = 0;
	int t1 = 1, t2 = 1;
	BFS(r, 0, map1, sum1, r1, t1);
	BFS(b, 0, map2, sum2, b1, t2);
	int ans = 0;
	for (auto item : map1)
	{

		ans += item.second*map2[item.first];
	}
	cout << ans;

	return 0;
}

Intelligent Recommendation

Interview Preparation ------ Algorithm Questions in the written test

There are n positive integers in the array. You can select one of them to multiply 2 or divide by 2 (for odds divided by 2 to take the integer part), so that the n numbers in the array become the same...

C ++ written test questions for school recruitment preparation

1. If you want to use the fopen function to open a new binary file, the file can be read and written, the file mode The string should be (). A “ab++” B “wb+” C “rb+&rdquo...

Hulu software development preparation 9.16 written test

Hulu offer, I have asked for a written exam 2020 previous questions 1 2021 previous year questions Face sutra 1 2 LeetCode 907. Sum of Subarray Minimums (Medium) 909. Snakes and Ladders (Medium) 2020 ...

Chengdu written test - PL / SQL preparation

1. English email writing First, you need to send an email to the customer, and the discussion of the needs determine a meeting time, we have time on Wednesday afternoon and Friday morning, interrogate...

Interview written test preparation (2) Sort algorithm

This article is a cow passenger network, a left-handed algorithm course class notes. (1) understanding of bubble sorting The first thing to remember is that bubble sorting gives an element to him to g...

More Recommendation

Interview written test preparation (3) Select algorithm

This article is a cow passenger network, a left-handed algorithm course class notes. (1) Curriculum explanation: Select Sort: At the beginning, the minimum value is selected on the entire array: place...

September 2020, C ++ written test preparation (5)

Chapter 5 Sharing and Protection of Data Scope Function prototype scope: The scope of the formal parameters in the function prototype declaration is the function of the function prototype. Local scope...

Written test preparation: character re -arrangement

Description: There is a string s, s, which may only be composed of lowercase letters and numbers. Please arrange the letters of the string according to the order of the English dictionary. The numbers...

Huawei written test - string sorting

Description of the topic Write a program that sorts the characters in the input string as follows. Rule 1: English letters are arranged from A to Z and are not case sensitive. For example, type: Type ...

[written test exercises] sorting algorithm

The IDE for testing is the Niuke.com: [1] Quick sort [2] heap sorting There are functions for heap operations in STL:  ...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top