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

1个回答

`````` #include<iostream>
#include<map>
#include<string>
#include<stack>
#include<vector>
using namespace std;
class Logic {
public:
Logic() {}                                      //构造函数
int priority(char);                               //获取运算符优先级
string trans(string);                             //中缀式->后缀式
double calculate();    //逻辑判断
void V_assign();                                  //变量赋值
string M_exp;                            //中缀式
string P_exp;                            //后缀式
map<string, double> variate;               //赋值序列
};
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;
cout << "后缀表达式：" << my.P_exp << endl;
cout << "赋值：" << endl;
my.V_assign();
cout<<"结果为："<<my.calculate();
return 0;
}
``````

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吗

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

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

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

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

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.

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语言的技术

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

Linux面试题（2020最新版）

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

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

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

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

MySQL数据库面试题（2020最新版）

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