ball ball各位大佬,C语言中序表达式树求值问题

给定一个如(x1+3.25)*(2.8-3.64)*x2的中缀表达式,输出其前中后序,输入数据更新变量的值以后求表达式值。这个怎么实现呀,我只会做全是常量的表达式求值。

1个回答

 #include<iostream>
#include<map>
#include<string>
#include<stack>
#include<vector>
using namespace std;
class Logic {
public:
    Logic() {}                                      //构造函数
    void Load(string);                                //input
    int priority(char);                               //获取运算符优先级
    string trans(string);                             //中缀式->后缀式
    double calculate();    //逻辑判断
    void V_assign();                                  //变量赋值
    string M_exp;                            //中缀式
    string P_exp;                            //后缀式
    map<string, double> variate;               //赋值序列
};
void Logic::Load(string str) {
    M_exp = str;;
    P_exp = trans(M_exp);             //处理数据(表达式转换)
}
int Logic::priority(char ch) {
    if (ch == '*'||ch=='/')
        return 2;
    if (ch == '+'||ch=='-')
        return 1;
    if (ch == '(')
        return -1;
    return 0;
}
double Logic::calculate() {
    string operators("+-*/");
    stack<double> res;            //此栈用作运算
    double a, b;
    for (int i = 0; i<P_exp.length(); i++) {
        if (operators.find(P_exp[i]) == string::npos) {      //遇到操作数,根据“字典”翻译后入栈
            res.push(variate[P_exp.substr(i, 1)]);
        }
        else {
            switch (P_exp[i]) {
            case '+':
                a = res.top();
                res.pop();
                b = res.top();
                res.pop();
                res.push(a + b);
                break;
            case '*':
                a = res.top();
                res.pop();
                b = res.top();
                res.pop();
                res.push(a * b);
                break;
            case '-':
                a = res.top();
                res.pop();
                b = res.top();
                res.pop();
                res.push(b-a);
                break;
            case '/':
                a = res.top();
                res.pop();
                b = res.top();
                res.pop();
                res.push(b/a);
                break;
            }
        }
    }
    return res.top();
}
string Logic::trans(string m_exp) {
    string p_exp;
    stack<char> stk;
    string operators("+-*/(");
    for (int i = 0; i < m_exp.length(); i++) {
        string one;
        if (operators.find(m_exp[i]) != string::npos) {      //出现操作符
            if (m_exp[i] == '(')         //栈中添加左括号
                stk.push(m_exp[i]);
            else {                      //操作符的优先级判断
                while ((!stk.empty()) && (priority(m_exp[i]) <= priority(stk.top()))) {    //当栈不为空时,进行优先级判断
                    p_exp.push_back(stk.top());   //若当前操作符优先级低于栈顶,弹出栈顶,放到后缀式中
                    stk.pop();
                }
                stk.push(m_exp[i]);             //将当前操作符入栈
            }
        }
        else if (m_exp[i] == ')') {            //出现右括号时,将栈中元素一直弹出,直至弹出左括号
            while (stk.top() != '(') {
                p_exp.push_back(stk.top());
                stk.pop();
            }
            stk.pop();                         //弹出左括号
        }
        else {           //把操作数加入到后缀式中
            variate[m_exp.substr(i, 1)] = 0;
            p_exp.push_back(m_exp[i]);
        }

    }
    while (!stk.empty()) {    //将栈中剩余操作符放到后缀式中
        p_exp.push_back(stk.top());
        stk.pop();
    }
    return p_exp;
}
void Logic::V_assign() {       //公式赋值
    int i = 0;
    for (auto it = variate.begin(); it != variate.end(); it++) {
        cout << "Enter the " << it->first << " : ";
        cin >> it->second;
    }
}
int main() {
    Logic my;
    string str;
    cin >> str;
    my.Load(str);
    cout << "后缀表达式:" << my.P_exp << endl;
    cout << "赋值:" << endl;
    my.V_assign();
    cout<<"结果为:"<<my.calculate();
    return 0;
}
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
C语言,Ball Toss

Description Classmates stand in a circle facing inward, each with the direction left or right in mind. One of the students has a ball and begins by tossing it to another student. (It doesn't really matter which one.)When one catches the ball and is thinking left, she throws it back across the circle one place to the left (from her perspective) of the person who threw her the ball. Then she switches from thinking left to thinking right. Similarly, if she is thinking right, she throws the ball to the right of the person who threw it to her and then switches from thinking right to thinking left. There are two exceptions to this rule: If one catches the ball from the classmate to her immediate left and is also thinking left, she passes the ball to the classmate to her immediate right, and then switches to thinking right. Similarly, if she gets the ball from the classmate to her immediate right and is thinking right, she passes the ball to the classmate to her immediate left, and then switches to thinking left.(Note that these rules are given to avoid the problem of tossing the ball to oneself.) No matter what the initial pattern of left and right thinking is and who first gets tossed the ball,everyone will get tossed the ball eventually! In this problem, you will figure out how long it takes. You'll be given the initial directions of n classmates (numbered clockwise), and the classmate to whom classmate 1 initially tosses the ball. (Classmate 1 will always have the ball initially.) Input There will be multiple problem instances. Each problem instance will be of the form n k t1 t2 t3 . . . tn where n (2 <= n <= 30) is the number of classmates, numbered 1 through n clockwise around the circle,k (> 1) is the classmate to whom classmate 1 initially tosses the ball, and ti (i = 1, 2, . . . , n) are eacheither L or R, indicating the initial direction thought by classmate i. (n = 0 indicates end of input.) Output For each problem instance, you should generate one line of output of the form: Classmate m got the ball last after t tosses. where m and t are for you to determine. You may assume that t will be no larger than 100,000. Note that classmate number 1 initially has the ball and tosses it to classmate k. Thus, number 1 has not yet been tossed the ball and so does not switch the direction he is thinking. Sample Input 4 2 L L L L 4 3 R L L R 10 4 R R L R L L R R L R 0 Sample Output Classmate 3 got the ball last after 4 tosses. Classmate 2 got the ball last after 4 tosses. Classmate 9 got the ball last after 69 tosses.

C语言的实现,Crystal Ball Factory 问题

Problem Description The Astrologically Clairvoyant Manufacturers (ACM),a pioneer in future-predicting technology, just landed a contract to manufacture crystal balls for weather forecasters around the world. Every week, a variable number of crystal balls needs to be delivered; the required amount for each week is specified in the contract. Crystal balls are made from the highest-quality crystal, whose price fluctuates from week to week. Fortunately, the ACM is able to foresee the price of crystal for the coming weeks, thanks to its own future-predicting technology. When the price is low, the ACM would like to buy crystal and manufacture crystal balls, storing any excess in their warehouse. On the other hand, in weeks for which the price is high, ACM would rather use the crystal balls stored in the warehouse to satisfy the demand specified in their contract. However, since there is a also a fixed weekly cost to store each crystal ball in the warehouse, and an initial cost for turning on the manufacturing machines and producing a non-zero quantity of crystal balls, the decision is not always simple. Can you help them fulfill their contract at minimal cost? Input The first line of each test case (representing a contract) will contain the number of weeks for which the contract will last. The next line will contain the non-negative integers b, k and n, where b is the base cost for manufacturing a non-zero quantity of crystal balls on a given week, k is the cost for storing each crystal ball in the warehouse for a week, and n is the maximum capacity of the warehouse. The following lines will describe the weeks specified in the contract in chronological order. Each week is described by a single line which will contain a pair of non-negative integers c and r, where c is the cost for manufacturing a new crystal ball using new crystal bought this week, and r is the number of crystal balls which must be delivered this week. A crystal ball can be manufactured and delivered in the same week if appropriate, in which case it won’t need to be stored in the warehouse at all. The last line of the input will contain the integer 0 and should not be processed. Output For each test case, output the minimum amount which the ACM will have to spend in order to fulfill the entire contract. All the numbers in the input will be at most 1000. Sample Input 4 1 0 1000 1 1 12 4 1 0 1000 1000 2 0 100 1 1 1000 1000 101 0 Sample Output 1007 101101

javascipt函数调用过程和值传递

``` <canvas id="canvas" style="border: 1px solid red ;" ></canvas> <script type="text/javascript"> var ball={x:512, y:100, r:20, g:2, vx:-4, vy:4, color:"#00FFFF"}//g重力加速度, window.onload=function(){ var canvas=document.getElementById("canvas"); canvas.width=768; canvas.height=768; var context=canvas.getContext("2d"); setInterval(function(){ render(context); update();},50) } function update(){ ball.x =ball.x+ball.vx; ball.y =ball.y+ball.vy; ball.vy =ball.vy+ball.g; if(ball.y>=768-ball.r)、 //请问这里的条件成立后,ball.y和ball.vy的值是值传递的吗? //两个ball.y和ball.vy传递之后,每调用update()方法是怎样是怎样的执行过程? { ball.y=768-ball.r; ball.vy=-ball.vy; } } function render(cxt){ cxt.clearRect(0,0,cxt.canvas.height,cxt.canvas.height); cxt.fillStyle=ball.color; cxt.beginPath(); cxt.arc(ball.x,ball.y,ball.r,0,2*Math.PI); cxt.closePath(); cxt.fill(); } </script> ```

sk-learn中KNN算法能动态的构建ball-tree吗

比如我用100个训练集去训练,训练完后我用一个数据的测试集去测试,测试完后我希望将这一个测试集加到训练集中去,必须重新构建这棵ball-tree吗(假设用的是这个树)?? 我看了ball-tree的那个5种构建树的论文:Five Balltree Construction Algorithms。论文中是说这5种构建树,其中2种是online,但sk-learn不知道怎么用 跪求大神指导!!万分感谢 贴上代码: X1=[[0,0],[2,4],[5,5],[10,10],[15,15]] Y1=[0,1,1,0,0] clf = neighbors.KNeighborsClassifier(algorithm="ball_tree", metric='euclidean',n_neighbors=5) clf.fit(X1,Y1) a=clf.predict([[1,3]]) print(a) 就是我想预测完[1,3]之后,希望将它加到之前构建的ball_tree中,而不是将[1,3]再加到X中重新fit,不知道有没有办法,求指教,急急急。万分感谢

请问大家这个问题用C语言怎么才能实现运行呢?总是超时间

Problem Description The princess is trapped in a magic place. In this place, there are N magic stones. In order to rescue the princess, you should destroy all the stones. The N stones are in a straight line. We number them as s1, s2, ... sn from left to right. Each stone has a magic strength m1, m2, ... mn. You have a powerful skill that can do some damage to the stones. To release the skill, you should stand to the right of some stone (si). Then you throw a power ball towards left. Initially, this ball has a power of p. When it hits a stone, it will do some damage to the stone and its power will be decreased, and the ball will continue to fly left to the next stone if its power is still positive. Formally, if you stand to the right of si and the power ball's initial power is p, then the ball will do Max(0, p - (i - j) * (i - j)) damage to sj, for each j <= i. So from this formula, we can see that the damage to stone sj is only determined by the initial power of the ball and the number of stones between si and sj. A stone is destroyed if the damage you do is larger than its magic strength. Note that even if a stone is destroyed, it will not disappear; your magic ball will do damage to it and the power will be decreased by that stone. You are not strong enough so that you can release at most k magic balls. It will cost a lot of energy if the power of the magic ball is too high. So what is the minimum value of p with which you can destroy all the magic stones, with no more than k magic balls? You can choose where to release each magic ball as your will, and the power of the ball must be a positive integer. Input The first line is the number of cases T (T ≤ 100). For each case, the first line gives two integers n, k (1 ≤ n ≤ 50000, 1 ≤ k ≤ 100000). The second line are n integers, giving m1, m2, ... mn (1 ≤ m ≤ 109). Output Print minimum possible p in a line. Sample Input 2 1 1 1 3 1 1 4 5 Sample Output 2 6

这里关于汇率的计算问题,采用C语言怎么实现汇率的计算的呢?

Problem Description Now that the Loonie is hovering about par with the Greenback, you have decided to use your $1000 entrance scholarship to engage in currency speculation. So you gaze into a crystal ball which predicts the closing exchange rate between Canadian and U.S. dollars for each of the next several days. On any given day, you can switch all of your money from Canadian to U.S. dollars, or vice versa, at the prevailing exchange rate, less a 3% commission, less any fraction of a cent. Assuming your crystal ball is correct, what's the maximum amount of money you can have, in Canadian dollars, when you're done? Input The input contains a number of test cases, followed by a line containing 0. Each test case begins with 0 <d &#8804; 365, the number of days that your crystal ball can predict. d lines follow, giving the price of a U.S. dollar in Canadian dollars, as a real number. Output For each test case, output a line giving the maximum amount of money, in Canadian dollars and cents, that it is possible to have at the end of the last prediction, assuming you may exchange money on any subset of the predicted days, in order. Sample Input 3 1.0500 0.9300 0.9900 2 1.0500 1.1000 0 Sample Output 1001.60 1000.00

给定的汇率然后计算转换的问题,如何运用C语言的形式去解决呢

Problem Description Now that the Loonie is hovering about par with the Greenback, you have decided to use your $1000 entrance scholarship to engage in currency speculation. So you gaze into a crystal ball which predicts the closing exchange rate between Canadian and U.S. dollars for each of the next several days. On any given day, you can switch all of your money from Canadian to U.S. dollars, or vice versa, at the prevailing exchange rate, less a 3% commission, less any fraction of a cent. Assuming your crystal ball is correct, what's the maximum amount of money you can have, in Canadian dollars, when you're done? Input The input contains a number of test cases, followed by a line containing 0. Each test case begins with 0 <d &#8804; 365, the number of days that your crystal ball can predict. d lines follow, giving the price of a U.S. dollar in Canadian dollars, as a real number. Output For each test case, output a line giving the maximum amount of money, in Canadian dollars and cents, that it is possible to have at the end of the last prediction, assuming you may exchange money on any subset of the predicted days, in order. Sample Input 3 1.0500 0.9300 0.9900 2 1.0500 1.1000 0 Sample Output 1001.60 1000.00

根据输入的半径值,计算球的体积,这个问题怎么采用C语言的编写的程序的代码的方式计算,运用什么公式?

Problem Description 根据输入的半径值,计算球的体积。 Input 输入数据有多组,每组占一行,每行包括一个实数,表示球的半径。 Output 输出对应的球的体积,对于每组输入数据,输出一行,计算结果保留三位小数。 Sample Input 1 1.5 Sample Output 4.189 14.137

碰撞的计算的算法的问题,怎么利用C语言的程序的设计的方式来实现的?

Problem Description Matt is playing a naive computer game with his deeply loved pure girl. The playground is a rectangle with walls around. Two balls are put in different positions inside the rectangle. The balls are so tiny that their volume can be ignored. Initially, two balls will move with velocity (1, 1). When a ball collides with any side of the rectangle, it will rebound without loss of energy. The rebound follows the law of refiection (i.e. the angle at which the ball is incident on the wall equals the angle at which it is reflected). After they choose the initial position, Matt wants you to tell him where will the two balls collide for the first time. Input The first line contains only one integer T which indicates the number of test cases. For each test case, the first line contains two integers x and y. The four vertices of the rectangle are (0, 0), (x, 0), (0, y) and (x, y). (1 ≤ x, y ≤ 105) The next line contains four integers x1, y1, x2, y2. The initial position of the two balls is (x1, y1) and (x2, y2). (0 ≤ x1, x2 ≤ x; 0 ≤ y1, y2 ≤ y) Output For each test case, output “Case #x:” in the first line, where x is the case number (starting from 1). In the second line, output “Collision will not happen.” (without quotes) if the collision will never happen. Otherwise, output two real numbers xc and yc, rounded to one decimal place, which indicate the position where the two balls will first collide. Sample Input 3 10 10 1 1 9 9 10 10 0 5 5 10 10 10 1 0 1 10 Sample Output Case #1: 6.0 6.0 Case #2: Collision will not happen. Case #3: 6.0 5.0

请求大佬支援!!为什么我的图片加载不出?

![图片说明](https://img-ask.csdn.net/upload/201905/10/1557480619_89273.png) ``` package tabletennis; import java.awt.*; import javax.swing.*; public class BallGame extends JFrame{ //加载图片 Image ball = Toolkit.getDefaultToolkit().getImage("img/ball.png"); Image desk = Toolkit.getDefaultToolkit().getImage("img/desk.jpg"); //画窗口方法 public void paint(Graphics g) { System.out.println("窗口被画了一次!"); g.drawImage(desk,0,0,null); g.drawImage(ball,100,100,null); } //窗口加载 void launchFrame() { setSize(300,300); setLocation(856,500); setVisible(true); } public static void main(String[] args) { BallGame ballgame = new BallGame(); ballgame.launchFrame(); } } ```

Ball Toss

Description Classmates stand in a circle facing inward, each with the direction left or right in mind. One of the students has a ball and begins by tossing it to another student. (It doesn't really matter which one.)When one catches the ball and is thinking left, she throws it back across the circle one place to the left (from her perspective) of the person who threw her the ball. Then she switches from thinking left to thinking right. Similarly, if she is thinking right, she throws the ball to the right of the person who threw it to her and then switches from thinking right to thinking left. There are two exceptions to this rule: If one catches the ball from the classmate to her immediate left and is also thinking left, she passes the ball to the classmate to her immediate right, and then switches to thinking right. Similarly, if she gets the ball from the classmate to her immediate right and is thinking right, she passes the ball to the classmate to her immediate left, and then switches to thinking left.(Note that these rules are given to avoid the problem of tossing the ball to oneself.) No matter what the initial pattern of left and right thinking is and who first gets tossed the ball,everyone will get tossed the ball eventually! In this problem, you will figure out how long it takes. You'll be given the initial directions of n classmates (numbered clockwise), and the classmate to whom classmate 1 initially tosses the ball. (Classmate 1 will always have the ball initially.) Input There will be multiple problem instances. Each problem instance will be of the form n k t1 t2 t3 . . . tn where n (2 <= n <= 30) is the number of classmates, numbered 1 through n clockwise around the circle,k (> 1) is the classmate to whom classmate 1 initially tosses the ball, and ti (i = 1, 2, . . . , n) are eacheither L or R, indicating the initial direction thought by classmate i. (n = 0 indicates end of input.) Output For each problem instance, you should generate one line of output of the form: Classmate m got the ball last after t tosses. where m and t are for you to determine. You may assume that t will be no larger than 100,000. Note that classmate number 1 initially has the ball and tosses it to classmate k. Thus, number 1 has not yet been tossed the ball and so does not switch the direction he is thinking. Sample Input 4 2 L L L L 4 3 R L L R 10 4 R R L R L L R R L R 0 Sample Output Classmate 3 got the ball last after 4 tosses. Classmate 2 got the ball last after 4 tosses. Classmate 9 got the ball last after 69 tosses.

计算货币的兑换的一个问题,怎么使用C语言的程序的编写的设计来解决的呢

Problem Description Now that the Loonie is hovering about par with the Greenback, you have decided to use your $1000 entrance scholarship to engage in currency speculation. So you gaze into a crystal ball which predicts the closing exchange rate between Canadian and U.S. dollars for each of the next several days. On any given day, you can switch all of your money from Canadian to U.S. dollars, or vice versa, at the prevailing exchange rate, less a 3% commission, less any fraction of a cent. Assuming your crystal ball is correct, what's the maximum amount of money you can have, in Canadian dollars, when you're done? Input The input contains a number of test cases, followed by a line containing 0. Each test case begins with 0 <d &#8804; 365, the number of days that your crystal ball can predict. d lines follow, giving the price of a U.S. dollar in Canadian dollars, as a real number. Output For each test case, output a line giving the maximum amount of money, in Canadian dollars and cents, that it is possible to have at the end of the last prediction, assuming you may exchange money on any subset of the predicted days, in order. Sample Input 3 1.0500 0.9300 0.9900 2 1.0500 1.1000 0 Sample Output 1001.60 1000.00

在正则表达式替换字符串中转义美元符号

<div class="post-text" itemprop="text"> <p>I have a function in which I need to replace "byte" with "$ball". This doesn't seem to work correctly. Here is the program snippet.</p> <pre><code>fun main() { str := []byte("$apple in a byte ") strReplace := "$ball" re := regexp.MustCompile("byte") final := re.ReplaceAll(str, []byte(strReplace)) ioutil.WriteFile("testfile.txt", final, 0744) } </code></pre> <p>Expected Output in testfile.txt: $apple in a $ball</p> <p>Actual Output in testfile.txt: $apple in a </p> <p>Any solutions for successfully getting the desired output?</p> </div>

Endless Spin用C语言实现

Problem Description I spin it again and again,and throw it away finally. So now I have a row of n ball,named from 1 to n,each ball is white initially. At each step I randomly chose a interval [l, r] and paint all ball in this interval to black. It means every interval have a equal chance of being chosen. And I'll stop if all ball are black.What is the expected steps before I stop? Input The first line contains integer T(1<=T<=50). Denoting the number of the test cases. Then T lines follows, each line contains an integer n (1<=n<=50). Output For each test cases,print the answer in a line. Print the answer rounded to 15 decimal places. Sample Input 3 1 2 3 Sample Output 1.000000000000000 2.000000000000000 2.900000000000000

Color the Ball

Description There are infinite balls in a line (numbered 1 2 3 ....), and initially all of them are paint black. Now Jim use a brush paint the balls, every time give two integers a b and follow by a char 'w' or 'b', 'w' denotes the ball from a to b are painted white, 'b' denotes that be painted black. You are ask to find the longest white ball sequence. Input First line is an integer N (<=2000), the times Jim paint, next N line contain a b c, c can be 'w' and 'b'. There are multiple cases, process to the end of file. Output Two integers the left end of the longest white ball sequence and the right end of longest white ball sequence (If more than one output the small number one). All the input are less than 2^31-1. If no such sequence exists, output "Oh, my god". Sample Input 3 1 4 w 8 11 w 3 5 b Sample Output 8 11

Ball bearings

Problem Description The Swedish company SKF makes ball bearings. As explained by Britannica Online, a ball bearing is “one of the two types of rolling, or anti friction, bearings (the other is the roller bearing). Its function is to connect two machine members that move relative to one another so that the frictional resistance to motion is minimal. In many applications, one of the members is a rotating shaft and the other a fixed housing. Each ball bearing has three main parts: two grooved, ring like races and a number of balls. The balls fill the space between the two races and roll with negligible friction in the grooves. The balls may be loosely restrained and separated by means of a retainer or cage.” Presumably, the more balls you have inside the outer ring, the smoother the ride will be, but how many can you t within the outer ring? You will be given the inner diameter of the outer ring, the diameter of the balls, and the minimum distance between neighboring balls. Your task is to compute the maximum number of balls that will t on the inside of the outer ring (all balls must touch the outer ring). Input The first line of input contains a positive integer n that indicates the number of test cases. Then follow n lines, each describing a test case. Each test case consists of three positive oating point numbers, D, d, s, where D is the inner diameter of the outer ring, d is the diameter of a ball, and s is the minimum distance between balls. All parameters are in the range [0.0001, 500.0]. Output For each test case output a single integer m on a line by itself, where m is the maximum number of balls that can t in the ball bearing, given the above constraints. There will always be room for at least three balls. Sample Input 2 20 1 0.1 100.0 13.0 0.2 Sample Output 54 20

Ball

N persons are going to attend a ball, in order to make acquaintance with other people. But they don't like to make friends with too many persons. As the organizer, you have asked each of them about the number of friends he wants to make acquaintance with. Assume that the ith person needs EXACTLY a[i] friends, how could you arrange their meets to satisfy all the needs of them? Perhaps you need a computer to help you. You are given the number of attendants and the exact number of friends each person wants to have, you must give out a configuration of acquaintances after your ball. Input The first line of each test case stands a integer N (1<=N<=100), which means the number of attendants to the ball. The second line contains N integers, which are the number of friends each person needs, the ith number a[i] means the ith person needs a[i] friends. The input ends up with N = 0, which should not be proceeded. Output If it is impossible to satisfy all the needs, print a single line "~><~". Otherwise, print out the configuration matrix of acquaintances after your arrangement. The matrix contains n lines and each line contains n integers (1 or 0). A '1' in the ith row and the jth column means the ith person have made friends with the jth person (of course that the jth person also made friends with the ith person), A '0' means they are not friends. Use exactly one space between two adjacent integers. Don't print any other character in the matrix. If there are multiple solutions for the needs, any one is acceptable. Print a blank line between two cases. Sample Input 2 2 2 2 1 1 0 Sample Output ~><~ 0 1 1 0

Simulation Wizardry C语言的技术

Description Simulation is an important application area in computer science involving the development of computer models to provide insight into real-world events. There are many kinds of simulation including (and certainly not limited to) discrete event simulation and clock-driven simulation. Simulation often involves approximating observed behavior in order to develop a practical approach. This problem involves the simulation of a simplistic pinball machine. In a pinball machine, a steel ball rolls around a surface, hitting various objects (bumpers) and accruing points until the ball ``disappears'' from the surface. You are to write a program that simulates an idealized pinball machine. This machine has a flat surface that has some obstacles (bumpers and walls). The surface is modeled as an m*n grid with the origin in the lower-left corner. Each bumper occupies a grid point. The grid positions on the edge of the surface are walls. Balls are shot (appear) one at a time on the grid, with an initial position, direction, and lifetime. In this simulation, all positions are integral, and the ball's direction is one of: up, down, left, or right. The ball bounces around the grid, hitting bumpers (which accumulates points) and walls (which does not add any points). The number of points accumulated by hitting a given bumper is the value of that bumper. The speed of all balls is one grid space per timestep. A ball ``hits'' an obstacle during a timestep when it would otherwise move on top of the bumper or wall grid point. A hit causes the ball to ``rebound'' by turning right (clockwise) 90 degrees, without ever moving on top of the obstacle and without changing position (only the direction changes as a result of a rebound). Note that by this definition sliding along a wall does not constitute ``hitting'' that wall. A ball's lifetime indicates how many time units the ball will live before disappearing from the surface. The ball uses one unit of lifetime for each grid step it moves. It also uses some units of lifetime for each bumper or wall that it hits. The lifetime used by a hit is the cost of that bumper or wall. As long as the ball has a positive lifetime when it hits a bumper, it obtains the full score for that bumper. Note that a ball with lifetime one will ``die'' during its next move and thus cannot obtain points for hitting a bumper during this last move. Once the lifetime is non-positive (less than or equal to zero), the ball disappears and the game continues with the next ball. Input Your program should simulate one game of pinball. There are several input lines that describe the game. The first line gives integers m and n, separated by a space. This describes a cartesian grid where 1 <= x <= m , 1 <= y <= n and on which the game is ``played''. It will be the case that 2 < m < 51 and 2 < n < 51. The next line gives the integer cost for hitting a wall. The next line gives the number of bumpers, an integer p >= 0 . The next p lines give the x position, y position, value, and cost, of each bumper, as four integers per line separated by space(s). The x and y positions of all bumpers will be in the range of the grid. The value and cost may be any integer (i.e., they may be negative; a negative cost adds lifetime to a ball that hits the bumper). The remaining lines of the file represent the balls. Each line represents one ball, and contains four integers separated by space(s): the initial x and y position of the ball, the direction of movement, and its lifetime. The position will be in range (and not on top of any bumper or wall). The direction will be one of four values: 0 for increasing x (right), 1 for increasing y (up), 2 for decreasing x (left), and 3 for decreasing y (down). The lifetime will be some positive integer. Output There should be one line of output for each ball giving an integer number of points accumulated by that ball in the same order as the balls appear in the input. After all of these lines, the total points for all balls should be printed. Sample Input 4 4 0 2 2 2 1 0 3 3 1 0 2 3 1 1 2 3 1 2 2 3 1 3 2 3 1 4 2 3 1 5 Sample Output 0 0 1 2 2 5

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

我以为我学懂了数据结构,直到看了这个导图才发现,我错了

数据结构与算法思维导图

String s = new String(" a ") 到底产生几个对象?

老生常谈的一个梗,到2020了还在争论,你们一天天的,哎哎哎,我不是针对你一个,我是说在座的各位都是人才! 上图红色的这3个箭头,对于通过new产生一个字符串(”宜春”)时,会先去常量池中查找是否已经有了”宜春”对象,如果没有则在常量池中创建一个此字符串对象,然后堆中再创建一个常量池中此”宜春”对象的拷贝对象。 也就是说准确答案是产生了一个或两个对象,如果常量池中原来没有 ”宜春” ,就是两个。...

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

Linux面试题(2020最新版)

文章目录Linux 概述什么是LinuxUnix和Linux有什么区别?什么是 Linux 内核?Linux的基本组件是什么?Linux 的体系结构BASH和DOS之间的基本区别是什么?Linux 开机启动过程?Linux系统缺省的运行级别?Linux 使用的进程间通信方式?Linux 有哪些系统日志文件?Linux系统安装多个桌面环境有帮助吗?什么是交换空间?什么是root帐户什么是LILO?什...

将一个接口响应时间从2s优化到 200ms以内的一个案例

一、背景 在开发联调阶段发现一个接口的响应时间特别长,经常超时,囧… 本文讲讲是如何定位到性能瓶颈以及修改的思路,将该接口从 2 s 左右优化到 200ms 以内 。 二、步骤 2.1 定位 定位性能瓶颈有两个思路,一个是通过工具去监控,一个是通过经验去猜想。 2.1.1 工具监控 就工具而言,推荐使用 arthas ,用到的是 trace 命令 具体安装步骤很简单,大家自行研究。 我的使用步骤是...

学历低,无法胜任工作,大佬告诉你应该怎么做

微信上收到一位读者小涛的留言,大致的意思是自己只有高中学历,经过培训后找到了一份工作,但很难胜任,考虑要不要辞职找一份他能力可以胜任的实习工作。下面是他留言的一部分内容: 二哥,我是 2016 年高中毕业的,考上了大学但没去成,主要是因为当时家里经济条件不太允许。 打工了三年后想学一门技术,就去培训了。培训的学校比较垃圾,现在非常后悔没去正规一点的机构培训。 去年 11 月份来北京找到了一份工...

JVM内存结构和Java内存模型别再傻傻分不清了

JVM内存结构和Java内存模型都是面试的热点问题,名字看感觉都差不多,网上有些博客也都把这两个概念混着用,实际上他们之间差别还是挺大的。 通俗点说,JVM内存结构是与JVM的内部存储结构相关,而Java内存模型是与多线程编程相关,本文针对这两个总是被混用的概念展开讲解。 JVM内存结构 JVM构成 说到JVM内存结构,就不会只是说内存结构的5个分区,而是会延展到整个JVM相关的问题,所以先了解下

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

Google 与微软的浏览器之争

浏览器再现“神仙打架”。整理 | 屠敏头图 | CSDN 下载自东方 IC出品 | CSDN(ID:CSDNnews)从 IE 到 Chrome,再从 Chrome 到 Edge,微软与...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

上班一个月,后悔当初着急入职的选择了

最近有个老铁,告诉我说,上班一个月,后悔当初着急入职现在公司了。他之前在美图做手机研发,今年美图那边今年也有一波组织优化调整,他是其中一个,在协商离职后,当时捉急找工作上班,因为有房贷供着,不能没有收入来源。所以匆忙选了一家公司,实际上是一个大型外包公司,主要派遣给其他手机厂商做外包项目。**当时承诺待遇还不错,所以就立马入职去上班了。但是后面入职后,发现薪酬待遇这块并不是HR所说那样,那个HR自...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

搜狗输入法也在挑战国人的智商!

故事总是一个接着一个到来...上周写完《鲁大师已经彻底沦为一款垃圾流氓软件!》这篇文章之后,鲁大师的市场工作人员就找到了我,希望把这篇文章删除掉。经过一番沟通我先把这篇文章从公号中删除了...

85后蒋凡:28岁实现财务自由、34岁成为阿里万亿电商帝国双掌门,他的人生底层逻辑是什么?...

蒋凡是何许人也? 2017年12月27日,在入职4年时间里,蒋凡开挂般坐上了淘宝总裁位置。 为此,时任阿里CEO张勇在任命书中力赞: 蒋凡加入阿里,始终保持创业者的冲劲,有敏锐的...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

什么时候跳槽,为什么离职,你想好了么?

都是出来打工的,多为自己着想

程序员为什么千万不要瞎努力?

本文作者用对比非常鲜明的两个开发团队的故事,讲解了敏捷开发之道 —— 如果你的团队缺乏统一标准的环境,那么即使勤劳努力,不仅会极其耗时而且成果甚微,使用...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发(16k)

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

终于懂了TCP和UDP协议区别

终于懂了TCP和UDP协议区别

无代码时代来临,程序员如何保住饭碗?

编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

立即提问
相关内容推荐