Didi 2017 Autumn Recruitment Programming Questions

[Programming question] Continuous maximum sum

Time limit: 1 second
Space limit: 32768K
An array has N elements, find the maximum sum of consecutive subarrays. For example: [-1,2,1], and the largest contiguous subarray is [2,1], whose sum is 3
Input Description: The
input is two lines.
The first line is an integer n (1 <= n <= 100000), indicating that there are a total of n elements.
The second line is n numbers, that is, each element, each integer is in the range of 32-bit int. separated by spaces.
Output description:
The sum of the largest value in all consecutive subarrays.
Input example 1:
3
-1 2 1
Output example 1:
3

Parse:

Use f[i] to represent the maximum element sum of the subarray ending with element i, then:
f[i] = a[i] , i==0 or f[i-1] < 0 (the sum of the previous elements is less than 0 , you can directly discard)
f[i] = f[i-1] + a[i] , f[i-1] > 0
and then find max(f[i]).

c++ code implementation:

#include <iostream>

using namespace std;

long long maxSubSum(int *a,int n)
{
    long long sum = 0;
    long long result = -2147483648;
    for(int i=0; i<n; i++){
        if(sum<=0)
            sum = a[i];
        else
            sum += a[i];
        if(sum > result)
            result = sum;
    }
    return result;
}

int main()
{
    int n;
    cin>>n;
    if(n<=0)
        return 0;
    int a[n];
    for(int i=0; i<n; i++){
       cin>>a[i];
    }
    cout<<maxSubSum(a,n);
    return 0;
}

[Programming question] Restaurant

Time limit: 1 second
Space limit: 32768K A
restaurant has n tables, each table has a parameter: a maximum number of people that can be accommodated; there are m batches of guests, each batch of guests has two parameters: b number of people, c estimated consumption amount . In the case that table sharing is not allowed, please implement an algorithm to select some of the guests so that the total expected consumption amount is the largest.
Input description: The
input includes m+2 lines.
The first line contains two integers n (1 <= n <= 50000), m (1 <= m <= 50000),
and the second line contains n parameters a, that is, the maximum number of people each table can accommodate, separated by spaces, the range Both are in the 32-bit int range.
Next m lines, each line with two parameters b, c. Respectively represent the number of guests in the i-th batch and the expected consumption amount, separated by spaces, and the range is within the range of 32-bit int.
Output description:
output an integer representing the maximum total expected consumption amount
Input example 1:
3 5
2 4 2
1 3
3 5
3 7
5 9
1 10
Output example 1:
20

Parse:

how are you. Sort the guest information in descending order of amount and ascending order of number of people. Then sort the table in ascending order by capacity. Then enumerate each batch of guests to find the current most suitable table capacity, using binary search.

C++ code implementation:

#include <iostream>
#include <algorithm>
#include <set>
using namespace std;

typedef struct{
    int num;
    int money;
}Customer;

unsigned long long maxIncoming(int n,int m,int *container,Customer* customer)
{
    multiset<int> table(container,container+n);
    sort(customer,customer+m,[](const Customer &c1,const Customer& c2){
        if(c1.money != c2.money)
            return c1.money > c2.money;
        return c1.num < c2.num;
    });
    unsigned long long total = 0;
    for(int i=0; i<m; i++){
        auto it = table.lower_bound(customer[i].num);
        if(it!=table.end()){
            total += customer[i].money;
            table.erase(it);
        }
    }
    return total;
}

int main()
{
    int n,m;
    cin>>n>>m;
    int container[n];
    Customer customer[m];
    for(int i=0; i<n; i++)
        cin>>container[i];
    for(int i=0; i<m; i++)
        cin>>customer[i].num>>customer[i].money;
    cout<<maxIncoming(n,m,container,customer);
    return 0;
}

[Programming question] Underground labyrinth

Time limit: 1 second
Space limit: 32768K
The little frog accidentally fell into an underground labyrinth one day, and the little frog hopes to jump out of the underground labyrinth with his only remaining stamina value P. In order to make the problem simple, suppose this is an n*m lattice maze, each position of the maze is 0 or 1, 0 means that there is an obstacle at this position, and the little frog cannot reach this position; 1 means that the little frog can reach the position. The little frog is initially at (0,0), and the exit of the underground maze is at (0,m-1) (guarantee that both positions are 1, and that there must be a reachable path from the start point to the end point), the little frog is in the maze It takes 1 stamina to move a unit distance horizontally, 3 units of stamina to climb a unit distance, and no stamina to move down. When the stamina of the frog is equal to 0, it has not yet reached the exit. The little frog will not be able to escape the maze. Now you need to help the little frog figure out whether it can jump out of the maze with the only remaining stamina (ie reach the (0,m-1) position).
Input description: The
input consists of n+1 lines:
the first line contains three integers n, m (3 <= m, n <= 10), P (1 <= P <= 100)
Next n lines:
m for each line A 0 or 1, separated by spaces
Output description:
If you can escape the maze, output a line of the path with the least physical energy consumption, the output format is shown in the example; if you cannot escape the maze, output "Can not escape!".
Test data guarantees unique answers
Input example 1:
4 4 10
1 0 0 1
1 1 0 1
0 1 1 1
0 0 1 1
Output example 1:
[0,0],[1,0],[1,1],[2,1],[2,2],[2,3],[1,3],[0,3]

Parse:

Deep search. Starting from the starting point, there are four directions to go. For each step, it is judged whether it has reached the exit and its physical strength is greater than 0. If it is, it means that a path has been found and the path information is updated; if it is not the exit, four directions are detected in turn. until all paths are traversed. The code is explained in detail.

C++ code implementation:

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

typedef struct Point{
    int row;
    int col;
    Point(int x,int y):row(x),col(y){}
    Point():row(0),col(0){}
}Point;

int direction[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};
int cost[4] = {0,-1,-3,-1};
int maze[10][10];
int n,m,p;
vector<Point> bestPath;
vector<Point> curPath;
int maxPower = 0x80000000;

void printPath()
{
    int i=0;
    for(; i<bestPath.size()-1; i++)
        cout<<"["<<bestPath[i].row<<","<<bestPath[i].col<<"],";
    cout<<"["<<bestPath[i].row<<","<<bestPath[i].col<<"]";
}

void findPath(int x,int y,int curPower)
{
    //将当前节点加入路径中标记为visited
    curPath.push_back(Point(x,y));
    maze[x][y] = 2;             //visited

    //到达出口,找到一条路径
    if(x==0 && y==m-1 && curPower>=0){  //找到一条路径
        if(curPower > maxPower){
            bestPath = curPath;
            maxPower = curPower;
        }
        curPath.pop_back();     //回退至上一步
        maze[x][y] = 1;         //还原
        return;
    }
    //当前节点并非出口,且体力不为0,则往4个方向上继续探测
    if(curPower>=0){
        for(int i=0; i<4; i++){
            int cx = x+direction[i][0];
            int cy = y+direction[i][1];
            int cp = curPower+cost[i];
            if(cx>=0 && cx<=n && cy>=0 && cy<=m && cp>=0 && maze[cx][cy]==1)
                findPath(cx,cy,cp);
        }
    }
    curPath.pop_back();     //回退至上一步
    maze[x][y] = 1;         //还原
}

int main()
{
    cin>>n>>m>>p;
    for(int i=0; i<n; i++){
        for(int j=0; j<m; j++)
            cin>>maze[i][j];
    }
    findPath(0,0,p);
    if(maxPower>=0)
        printPath();
    else
        cout<<"Can not escape!";
    return 0;
}

[Programming question] The number of 0 at the end

Time limit: 1 second
Space limit: 32768K
Enter a positive integer n, how many 0s are at the end of n! (ie factorial)? For example: n = 10; n! = 3628800, so the answer is 2
Input description:
input is one line, n (1 ≤ n ≤ 1000)
output description:
output an integer, which is what the question requires
Input example 1:
10
Output example 1:
2

Parse

Analyze under what circumstances will the trailing 0 appear?
(1) Multiply 5 (the 5 at the end of the number) by an even number, and the result must be 0;
(2) If the end of the number is 0, the result is also 0;
the second can be converted into the form of 5*x, such as 15=5* 3, 25=5*5
Therefore, calculate n! To find the number of trailing 0s in the result, you only need to find the number of factors of 5 in [1-n] n numbers.
Note: Similar to 25, it can be split into 5*5, need attention.

C++ code implementation:

#include <iostream>
using namespace std;

int endWithZero(int n)
{
    if(n<5)
        return 0;
    int count = 0, i,j;
    for(i=5; i<=n; i+=5){
        j = i;
        while(j%5==0){
            count++;
            j /= 5;
        }
    }
    return count;
}

int main()
{
    int n;
    cin>>n;
    if(n<1 || n>1000)
        return 0;
    cout<<endWithZero(n);
    return 0;
}

[Programming question] Hexadecimal conversion

Time limit: 1 second
Space limit: 32768K
Given a decimal number M, and a decimal number N that needs to be converted. Convert decimal number M to N-ary number
Input description: The
input is one line, M (32-bit integer), N (2 ≤ N ≤ 16), separated by spaces.
Output description:
Output the converted number for each test instance, one line per output. If N is greater than 9, the corresponding number rule refers to hexadecimal (for example, 10 is represented by A, etc.)
Input example 1:
7 2
Output example 1:
111

Parse:

(1) Pay attention to the negative number, which needs to be converted into a positive number;
(2) If it is -2147483648, the positive number of the conversion bit is 214748648, which exceeds the range of 32-bit int, so unsigned int or long must be used.

c++ code implementation:

#include <iostream>

using namespace std;

string factor = "0123456789ABCDEF";

void decToN(int num,int n)
{
    if(num==0){
        cout<<0;
        return;
    }
    bool flag = true;
    unsigned int m = 0;
    if(num<0){
        m = ~num + 1;   //注意-2147483648 ~ 2147483647
        flag = false;
    }
    else
        m = num;
    int index = 31;
    char str[32]={0};
    while(m!=0){
        str[index--] = factor[m%n];
        m /= n;
    }
    if(!flag)
        cout<<'-';
    for(int i=index+1; i<32; i++)
        cout<<str[i];
}

int main()
{
    int m,n;
    cin>>m>>n;
    if(n<2 || n>16)
        return 0;
    decToN(m,n);
    return 0;
}

[Programming question] Number and the number of methods for sum

Time limit: 1 second
Space limit: 32768K
Given an array A with n positive integers and an integer sum, find the number of solutions that select the sum of some numbers in array A as sum.
When two selection schemes have a different subscript of a number, we consider them to be different composition schemes.
Input description: The
input is two lines:
the first line is two positive integers n (1 ≤ n ≤ 1000), and
the second line is n positive integers A i separated by spaces.
Output description:
Output the number of solutions required
Input example 1:
5 15
5 5 10 2 3
Output example 1:
4

Parse:

(1) Deep search. Sort the array in descending order first. Then use deep search. Note that recursion tends to time out and requires an extra array to hold intermediate results.
(2) Dynamic programming. dp[i][j] represents the first i elements and the number of solutions for j.
Initial: dp[i][0] = 1 (all elements are not taken, then the sum is 0), dp[0][j] = 0;
Derivation equation:
dp[i][j] = dp[i-1 ] j + dp[i-1][j-num[i]] (take the i-th element), if(j>=num[i])
dp[i][j] = dp[i-1][ j], if (j < num[i]).

C++ code implementation:
deep search

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

int num[1000] = {0};
int sum = 0;
int n = 0;
vector<vector<long long>> dp;

long long dfs(int last,int restSum)
{
    if(restSum==0)
        return 1;
    if(dp[last][restSum]!=-1)
        return dp[last][restSum];
    long long count = 0;
    for(int i=last; i<n; i++){
        if(restSum >= num[i])
            count += dfs(i+1,restSum-num[i]);
    }
    dp[last][restSum] = count;
    return count;
}

long long numberOfSum()
{
    sort(num,num+n,greater<int>());
    return dfs(0,sum);
}

int main()
{
    cin>>n>>sum;
    dp.resize(n+1,vector<long long>(sum+1,-1));
    for(int i=0; i<n; i++)
        cin>>num[i];
    cout<<numberOfSum();
    return 0;
}

dynamic programming

#include <iostream>
using namespace std;

int num[1000] = {0};
int sum = 0;
int n = 0;
long long dp[1001][1001]={0};


long long numberOfSum()
{
    for(int j=0; j<1001; j++)
        dp[0][j] = 0;
    for(int i=0; i<1001; i++)
        dp[i][0] = 1;         //前i个元素和为0只有一种方案,就是全都不取

    for(int i=1; i<=n; i++){
        for(int j=0; j<=sum; j++){
            if(j>=num[i-1])
                dp[i][j] = dp[i-1][j] + dp[i-1][j-num[i-1]];
            else
                dp[i][j] = dp[i-1][j];
        }
    }
    return dp[n][sum];
}

int main()
{
    cin>>n>>sum;
    for(int i=0; i<n; i++)
        cin>>num[i];
    cout<<numberOfSum();
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326285759&siteId=291194637
Recommended