数据结构stack两发

C - Matrix Chain Multiplication(Stack应用)

 There is a famous railway station in PopPush City. Country there is incredibly hilly. The station was built in last century. Unfortunately, funds were extremely limited that time. It was possible to establish only a surface track. Moreover, it turned out that the station could be only a dead-end one (see picture) and due to lack of available space it could have only one track.

The local tradition is that every train arriving from the direction A continues in the direction B with coaches reorganized in some way. Assume that the train arriving from the direction A has N <= 1000 coaches numbered in increasing order 1, 2, ..., N. The chief for train reorganizations must know whether it is possible to marshal coaches continuing in the direction B so that their order will be a1, a2, ..., aN. Help him and write a program that decides whether it is possible to get the required order of coaches. You can assume that single coaches can be disconnected from the train before they enter the station and that they can move themselves until they are on the track in the direction B. You can also suppose that at any time there can be located as many coaches as necessary in the station. But once a coach has entered the station it cannot return to the track in the direction A and also once it has left the station in the direction B it cannot return back to the station.

Input
The input consists of blocks of lines. Each block except the last describes one train and possibly more requirements for its reorganization. In the first line of the block there is the integer N described above. In each of the next lines of the block there is a permutation of 1, 2, ..., N. The last line of the block contains just 0.

The last block consists of just one line containing 0.
Output
The output contains the lines corresponding to the lines with permutations in the input. A line of the output contains Yes if it is possible to marshal the coaches in the order required on the corresponding line of the input. Otherwise it contains No. In addition, there is one empty line after the lines corresponding to one block of the input. There is no line in the output corresponding to the last ``null'' block of the input.
Sample Input
5
1 2 3 4 5
5 4 1 2 3
0
6
6 5 4 3 2 1
0
0
Sample Output
Yes
No

Yes
    题意:火车进入A,按1-n排列,可以直接按顺序进入B,也可以通过C进行中转,C中符合后进先出,给出出B的序列,问是否能这样出站?

       解析:后进先出,使用栈,stack。a=1,b=1来同时表示了AB站的当前火车编号和剩余车厢数量。代码里标上语句的具体作用,最后注意输出格式。

#include <iostream>
#include<stack>
using namespace std;
typedef long long ll;
const int maxn=1e3+10;
int B[maxn];
int main()
{
    int n;
    while(cin>>n&&n)
    {
        while(cin>>B[1]&&B[1])
        {
            for(int i=2;i<=n;i++)
                cin>>B[i];
            stack<int>s;
            int a=1,b=1;
            int ok=0;
            while(b<=n)    
            {
                if(a==B[b])    //如果A站车头==B站车头,直接进入B站
                    a++,b++;
                else if(!s.empty()&&B[b]==s.top())  //如果C站车尾等于B站车头,直接从C进入B
                    {
                        b++;
                        s.pop();
                    }
                else if(a<=n)      //以上条件都不符合而且A中还有车,那么把车进入C进行中转。
                    {
                        s.push(a);
                        a++;
                    }
                else            //都不符合而且A站没车了,break掉,NO
                    {
                        ok=1;break;
                    }
            }
            if(ok)
                cout<<"No"<<endl;
            else
                cout<<"Yes"<<endl;
        }
        cout<<endl;
    }
}

    另一种代码:比较巧妙了,并不需要繁琐的判断。直接让1-n进栈,每次的进栈,我们就判断。比如进入一个i,它直接就等于B站的第一个,那么就出栈,这个操作和直接从A->B是一样的。最后

只要栈空了,就是Yes,否则就是No。

#include <iostream>
#include<stack>
using namespace std;
typedef long long ll;
const int maxn=1e3+10;
int B[maxn];
int main()
{
    int n;
    while(cin>>n&&n)
    {
        while(cin>>B[1]&&B[1])
        {
            for(int i=2;i<=n;i++)
                cin>>B[i];
            stack<int>s;
            int a=1,k=1;
            for(int i=1;i<=n;i++)
            {
                s.push(i);
                while(!s.empty()&&s.top()==B[k])
                {
                    k++;
                    s.pop();
                }
            }
            if(!s.empty())
                cout<<"No"<<endl;
            else
                cout<<"Yes"<<endl;
        }
        cout<<endl;
    }
}

UVA442-Matrix Chain Multiplication(Stack应用)

Suppose you have to evaluate an expression like A*B*C*D*E where A,B,C,D and E are matrices. Since matrix multiplication is associative, the order in which multiplications are performed is arbitrary. However, the number of elementary multiplications needed strongly depends on the evaluation order you choose.

For example, let A be a 50*10 matrix, B a 10*20 matrix and C a 20*5 matrix. There are two different strategies to compute A*B*C, namely (A*B)*C and A*(B*C).

The first one takes 15000 elementary multiplications, but the second one only 3500.

Your job is to write a program that determines the number of elementary multiplications needed for a given evaluation strategy.

Input Specification

Input consists of two parts: a list of matrices and a list of expressions.

The first line of the input file contains one integer n ( tex2html_wrap_inline28 ), representing the number of matrices in the first part. The next n lines each contain one capital letter, specifying the name of the matrix, and two integers, specifying the number of rows and columns of the matrix.

The second part of the input file strictly adheres to the following syntax (given in EBNF):

SecondPart = Line { Line } <EOF>
Line = Expression <CR>
Expression = Matrix | “(” Expression Expression “)”
Matrix = “A” | “B” | “C” | … | “X” | “Y” | “Z”

Output Specification

For each expression found in the second part of the input file, print one line containing the word “error” if evaluation of the expression leads to an error due to non-matching matrices. Otherwise print one line containing the number of elementary multiplications needed to evaluate the expression in the way specified by the parentheses.

Sample Input

9
A 50 10
B 10 20
C 20 5
D 30 35
E 35 15
F 15 5
G 5 10
H 10 20
I 20 25
A
B
C
(AA)
(AB)
(AC)
(A(BC))
((AB)C)
(((((DE)F)G)H)I)
(D(E(F(G(HI)))))
((D(EF))((GH)I))

Sample Output

0
0
0
error
10000
error
3500
15000
40500
47500
15125
    题意:输入n个矩阵的维度和一些矩阵链乘表达式,输出乘法的次数。如果乘法无法进行,输出error。假定A是m*n矩阵,B是n*p矩阵,那么AB是m*p矩阵,乘法次数为m*n*p。如果A的列数不等于B的行数,则乘法无法进行。例如,A是50*10的,B是10*20的,C是20*5的,则(A(BC))的乘法次数为10*20*5(BC的乘法次数)+ 50*10*5((A(BC))的乘法次数)= 3500。

    计算那里是有点饶,具体的就看代码吧,遇到 ' ) '  就计算。记录时坐标按-'A'即可。

#include <iostream>
#include<stack>
using namespace std;
typedef long long ll;
struct node
{
    int x,y;
}st[29];
stack<node>s;
int main()
{
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        char ch[2];
        cin>>ch;
        int mid=ch[0]-'A';
        cin>>st[mid].x>>st[mid].y;    
    }    
    string ss;
    while(cin>>ss)
    {
        int len=ss.length();
        if(len==1)
            {
                cout<<"0"<<endl;continue;
            }
        int ok=0;
        int ans=0;
        for(int i=0;i<len;i++)
        {
            if(ss[i]=='(')
                continue;
            if(ss[i]>='A'&&ss[i]<='Z')
            {
                s.push(st[ss[i]-'A']);
            }
            if(ss[i]==')')
            {
                node t1=s.top();s.pop();
                node t2=s.top();s.pop();
                if(t2.y!=t1.x)
                {
                    ok=1;
                    cout<<"error"<<endl;break;
                }
                ans+=t2.x*t2.y*t1.y;
                node t3;
                t3.x=t2.x;t3.y=t1.y;
                s.push(t3); 
            }
        }
        if(!ok)
            cout<<ans<<endl;
    }
}



 

原文地址:https://www.cnblogs.com/liyexin/p/12343659.html