SDUT OJ 编译原理

A - 小C语言--词法分析程序

Description

小C语言文法 
1. <程序>→<main关键字>(){<声明序列><语句序列>}
2. <声明序列>→<声明序列><声明语句>|<声明语句>|<空>
3. <声明语句>→<标识符表>;
4. <标识符表>→<标识符>,<标识符表>|<标识符>
5. <语句序列>→<语句序列><语句>|<语句>
6. <语句>→< if语句>|< while语句>|< for语句>|<复合语句>|<赋值语句>
7. < if语句>→< if关键字>(<表达式>)<复合语句>|(<表达式>)<复合语句>< else关键字><复合语句>
8. < while语句>→< while关键字>(<表达式>)<复合语句>
9. < for语句>→< for关键字>(<表达式>;<表达式>;<表达式>)<复合语句>
10. <复合语句>→{<语句序列>}
11. <赋值语句>→<表达式>;
12. <表达式>→<标识符>=<算数表达式>|<布尔表达式>
13. <布尔表达式>→<算数表达式> |<算数表达式><关系运算符><算数表达式>
14. <关系运算符>→>|<|>=|<=|==|!=
15. <算数表达式>→<算数表达式>+<项>|<算数表达式>-<项>|<项>
16. <项>→<项>*<因子>|<项>/<因子>|<因子>
17. <因子>→<标识符>|<无符号整数>|(<算数表达式>)
18. <标识符>→<字母>|<标识符><字母>|<标识符><数字>
19. <无符号整数>→<数字>|<无符号整数><数字>
20. <字母>→a|b|…|z|A|B|…|Z
21. <数字>→0|1|2|3|4|5|6|7|8|9

22. < main关键字>→main
23. < if关键字>→if
24. < else关键字>→else
25. < for关键字>→for
26. < while关键字>→while
27. < int关键字>→int

每行单词数不超过10个
小C语言文法如上,现在我们对小C语言写的一个源程序进行词法分析,分析出关键字、自定义标识符、整数、界符
和运算符。
关键字:main if else for while int
自定义标识符:除关键字外的标识符
整数:无符号整数
界符:{ } ( ) , ;
运算符:= + - * / < <= > >= == !=

Input

输入一个小C语言源程序,源程序长度不超过2000个字符,保证输入合法。

Output

按照源程序中单词出现顺序输出,输出二元组形式的单词串。

(单词种类,单词值)

单词一共5个种类:

关键字:用keyword表示
自定义标识符:用identifier表示
整数:用integer表示
界符:用boundary表示
运算符:用operator表示

每种单词值用该单词的符号串表示。

Samples

Sample #1
Input 

main()

{

        int a, b;

        if(a == 10)

        {

                a = b;

        }

}

Output 
(keyword,main)
(boundary,()
(boundary,))
(boundary,{)
(keyword,int)
(identifier,a)
(boundary,,)
(identifier,b)
(boundary,;)
(keyword,if)
(boundary,()
(identifier,a)
(operator,==)
(integer,10)
(boundary,))
(boundary,{)
(identifier,a)
(operator,=)
(identifier,b)
(boundary,;)
(boundary,})
(boundary,})
#include<bits/stdc++.h>
using namespace std;
string KeyWord[6] = {"main", "for", "if", "else", "int", "while"};
string category[5] = {"keyword", "identifier", "integer", "boundary", "operator"};
void disp(string s){// 输入进来的有keyword、identifier、integer,其余在已经主程序里判断
    // 数字直接判断
    if(s[0] >= '0' && s[0] <= '9') cout << "(integer," << s << ")" << endl; 
    else{
        bool flag = 1;
        for(int i = 0; i < 6; i++){
            if(s == KeyWord[i]){
                flag = 0;
                cout << "(keyword," << s << ")" << endl;
            }
        }
        if(flag == 1) cout << "(identifier," << s << ")" << endl;
    }
}
int main()
{
    string str;
    while(cin >> str){
        int len = str.length();
        string temp = "";
        for(int i = 0; i < len; i++){
            if(str[i] == '(' || str[i] == ')' || str[i] == '{' || 
                str[i] == '}' || str[i] == ',' || str[i] == ';'){
                if(temp.length()) disp(temp);
                temp = "";
                cout << "(boundary," << str[i] << ")" << endl;

            }
            else if(str[i] == '=' || str[i] == '+' || str[i] == '-' || str[i] == '*' ||
             str[i] == '/' || str[i] == '<' || str [i]== '>' || str[i] == '!'){
                if(temp.length()){// 如果temp不为空
                    disp(temp);
                }
                temp = "";
                if(str[i + 1] == '='){// 输出>= <= == !=之类的情况
                    cout << "(operator," << str[i] << str[i+1] << ")" << endl;
                    i++;// 上面输出了两个字符,所以要加一
                }
                else cout << "(operator," << str[i] << ")" << endl;
            }
            else temp += str[i];
        }
        if(temp.length()) disp(temp);
    }
    return 0;    
}

D - 表达式语法分析——递归子程序法

Description

 

递归子程序法是一种确定的自顶向下语法分析方法,要求文法是LL(1)文法。它的实现思想是对应文法中每个非终结符编写一个递归过程,每个过程的功能是识别由该非终结符推出的串,当某非终结符的产生式有多个候选式时能够按LL(1)形式唯一地确定选择某个候选式进行推导。请根据下面的表达式LL(1)文法,构造递归子程序,完成对表达式的语法分析。

表达式文法如下:

    E→TG

    G→+TG | ε

    T→FS

    S→*FS | ε

    F→(E) | i


对于给定的输入串(长度不超过50个符号),请输出分析过程中用到的所有产生式,并指明该输入串是否为该文法能生成的表达式,输出共11行,前10行每行两个数据用空格隔开,表示推导时所用产生式顺序号(从0开始),最后一行是accept,表示i+i*i是文法能生成的合法表达式。注:其中&符号代表文法中的ε符号。
例如:

i+i*i是文法能生成的一个表达式,输出格式如下:

0 E-->TG

1 T-->FS

2 F-->i

3 S-->&

4 G-->+TG

5 T-->FS

6 F-->i

7 S-->*FS

8 F-->i

9 S-->&

10 G-->&

accept


i@i不是文法能生成的表达式,输出共5行,前5行每行两个数据用空格隔开,表示推导时所用产生式序号(从0开始),最后一行是error,表示i@i不是文法能生成的表达式。@不是合法的文法符号,输出格式举例:

0 E-->TG

1 T-->FS

2 F-->i

3 S-->&

4 G-->&

error

 

(i+i*i不是文法能生成的表达式,存在括号不匹配的语法错误,输出格式举例:

0 E-->TG

1 T-->FS

2 F-->(E)

3 E-->TG

4 T-->FS

5 F-->i

6 S-->&

7 G-->+TG

8 T-->FS

9 F-->i

10 S-->*FS

11 F-->i

12 S-->&

13 G-->&

error

Input

输入数据只有一行,代表待分析的符号串,以#号结束

Output

输出推导过程中所有的产生式,按照使用顺序给出。输出详细说明见题目描述中的例子。

Samples

Sample #1
Input 

i+i*i#

Output 
0 E-->TG
1 T-->FS
2 F-->i
3 S-->&
4 G-->+TG
5 T-->FS
6 F-->i
7 S-->*FS
8 F-->i
9 S-->&
10 G-->&
accept
#include<bits/stdc++.h>
using namespace std;

const int N = 55;
char str[N];
int cnt, i;

void E();
void G();
void T();
void S();
void F();

void E(){
    if(str[i] == '(' || str[i] == 'i'){
        printf("%d E-->TG\n", cnt++);
        T();G();
    } else{
        printf("error\n");
        exit(0);
    }
}
void G(){
    if(str[i] == '+'){
        printf("%d G-->+TG\n", cnt++);
        i++;
        T();G();
    }else{
        printf("%d G-->&\n", cnt++);
    }
}
void T(){
    if(str[i] == '(' || str[i] == 'i'){
        printf("%d T-->FS\n", cnt++);
        F();S();
    }else{
        printf("error\n");
        exit(0);
    }
}
void S(){
    if(str[i] == '*'){
        printf("%d S-->*FS\n", cnt++);
        i++;
        F();S();
    }else{
        printf("%d S-->&\n", cnt++);
    }
}
void F(){
    if(str[i] == '('){
        printf("%d F-->(E)\n", cnt++);
        i++;
        E();
        if(str[i] == ')'){
            i++;
        }else{
            printf("error\n");
            exit(0);
        }
    }else if(str[i] == 'i'){
        printf("%d F-->i\n", cnt++);
        i++;
    }else{
        printf("error\n");
        exit(0);
    }
}


int main()
{
    scanf("%s", str);
    E();
    if(str[i] != '#'){
        printf("error\n");
    } else{
        printf("accept\n");
    }
    return 0;
}

N - 翻译布尔表达式

Description

大家都学过了布尔表达式的翻译,其中有一个拉链-回填技术,这次我们就练习这个技术。

Input

输入为一行字符串,例如: a < b or c < d and e < f

每个符号都用空格间隔。

其中逻辑运算符包含 and 和 or , 关系运算符包含 < 、> 、<= 、 >= 、== 、 != 。

Output

 假链跳到0,真链跳到1,表达式序号从100开始排。

Samples

Sample #1
Input 
Output 
a < b or c < d and e < f
100(j<,a,b,1)
101(j,_,_,102)
102(j<,c,d,104)
103(j,_,_,0)
104(j<,e,f,100)
105(j,_,_,103)
#include<bits/stdc++.h>
using namespace std;

string str, x;
int num = 100, True = 1, False = 100;// 序号、真、假
vector<string>v;
int main()
{
    //cin >> str; 无法输入空格
    getline(cin, str);
    str += " #"; // 自己额外加的一个结束标志
    stringstream strr(str);// 
    while(strr >> x){// 以空格为分割点,将str中的字符(串)赋给x
        if(x == "or" || x == "#"){
            if(x == "or") False += 2;
            else False = 0;
            int len = v.size();
            for(int i = 0; i < len - 3; i += 3){
                printf("%d(j%s,%s,%s,%d)\n", num, v[i+1].c_str(), v[i].c_str(), v[i+2].c_str(), num + 2);// 真链
                num ++;
                printf("%d(j,_,_,%d)\n", num, False);// 假链
                False = num++;
            }
            printf("%d(j%s,%s,%s,%d)\n", num, v[len-2].c_str(), v[len - 3].c_str(), v[len - 1].c_str(), True);
            True = num ++;
            printf("%d(j,_,_,%d)\n", num, False);
            num++;
            v.clear();
            if(x == "#") break;// 读到结束符停止
        }
        else if(x == "and") False += 2;
        else v.push_back(x);
    }
    return 0;
}

O - DAG优化

Description

大家都学过了代码优化,其中有一个DAG优化,这次我们就练习这个操作。

Input

输入第一行为一个整数n(n < 100),表示该组输入的表达式的个数

之后n行为表达式,每个变量为一个字母,表达式仅包括二元运算 + - * /

例如:A=B+C

Output

 通过构造DAG图,进行代码优化,只需要保留AB,删除无用变量,删除变量时,尽量保留最早出现的变量。

PS:保证AB的值不同

Samples

Sample #1
Input 
Output 
3
A=B+C
B=B+B
A=C+C
B=B+B
A=C+C
#include <bits/stdc++.h>
using namespace std;
string s;
int flag[110];
char ans[110][110];
int n,num=0;
struct node
{
    int l=-1,r=-1;
    char id;
    vector<char>val;
}t[110];
int find(int x,char ch)
{
    for(char c:t[x].val)
        if(c==ch)return 1;
    return 0;
}
int add(char ch)
{
    for(int i=num-1;i>=0;i--)
        if(ch==t[i].id||find(i,ch))return i;
    t[num].id=ch;
    return num++;
}
void add_op(char op,char ch,int l, int r)
{
    for(int i=num-1;i>=0;i--)
        if(t[i].id==op&&t[i].l==l&&t[i].r==r)
    {
        t[i].val.push_back(ch);return;
    }
    t[num].id=op;
    t[num].l=l;
    t[num].r=r;
    t[num].val.push_back(ch);
    num++;
}
void dfs(int x)
{
    if(t[x].l!=-1)
    {
        flag[x]=1;
        dfs(t[x].l);
        dfs(t[x].r);
    }
}
char exist(int x)
{
    char ans=0;
    for(char c:t[x].val)
        if(c=='A'||c=='B')ans=c;
    return ans!=0?ans:t[x].val[0];
}
int main()
{
    cin>>n;
    for(int i=0;i<n;i++)
    {
        cin>>s;
        int l=add(s[2]);
        int r=add(s[4]);
        add_op(s[3],s[0],l,r);
    }
    for(int i=0;i<num;i++)
    {
        if(t[i].l!=-1)
        {
            ans[i][0]=exist(i);
            ans[i][1]='=';
            ans[i][2]=t[t[i].l].val.size()>0?exist(t[i].l):t[t[i].l].id;
            ans[i][3]=t[i].id;
            ans[i][4]=t[t[i].r].val.size()>0?exist(t[i].r):t[t[i].r].id;
            ans[i][5]='\0';
        }
    }
    for(int i=num-1;i>=0;i--)
    {
        if(ans[i][0]=='A')
        {
            dfs(i);break;
        }
    }
    for(int i=num-1;i>=0;i--)
    {
        if(ans[i][0]=='B')
        {
            dfs(i);break;
        }
    }
    for(int i=0;i<num;i++)
        if(flag[i])cout<<ans[i]<<endl;
}

P - 简单的代码生成程序

Description

通过三地址代码序列生成计算机的目标代码,在生成算法中,对寄存器的使用顺序为:寄存器中存有 > 空寄存器 > 内存中存有 > 以后不再使用 > 最远距离使用

Input

单组输入,给定输出的三地址代码的个数和寄存器的个数.所有的变量为大写字母,寄存器的数量不超过9

Output

参照示例格式输出,不需要将最后的寄存器中的值写回内存

不再使用变量不用写回内存

Samples

Sample #1
Input 
Output 
4 2
T:=A-B
U:=A-C
V:=T+U
W:=V+U
LD R0, A
SUB R0, B
LD R1, A
SUB R1, C
ADD R0, R1
ADD R0, R1
#include<bits/stdc++.h>
using namespace std;
int n, m, top = 0;
char p[10], s[110][1100];
int get(char ch)
{
    for(int i = 0; i < m; i++){
        if(p[i] == ch) return i;
    }
    return -1;
}
int use(int x, char ch)
{
    for(int i = x; i < n; i++){
        if(ch == s[i][3] || ch == s[i][5]) return i;
    }
    return n;
}
int findd(int x)
{
    if(top < m) return top++;
    int t = -1, maxn = -1;
    for(int i = 0; i < m; i++){
        int k = use(x, p[i]);
        if(k > maxn){
            maxn = k;
            t = i;
        }
    }
    return t;
}
void print1(char ch)
{
	if(ch=='+')cout<<"ADD ";
	else if(ch=='-')cout<<"SUB ";
	else if(ch=='*')cout<<"MUL ";
	else if(ch=='\\')cout<<"DIV ";
}
void print2(char ch)
{
    int x = get(ch);
    if(x != -1) cout << "R" << x << "\n";
    else cout << ch << "\n";
}
int main()
{
    cin >> n >> m;
    for(int i = 0; i < n; i++){
        cin >> s[i];
    }
    for(int i = 0; i < n; i++){
        int x = get(s[i][3]);
        if(x == -1){
            x = findd(i);
            if(p[x] != '\0' && use(i, p[x]) < n){
                cout << "ST R" << x << ", " << p[x] << "\n";
                p[x] = NULL;
            }
            cout << "LD R" << x << ", " << s[i][3] << "\n";
        }
        print1(s[i][4]);
        cout << "R" << x << ", ";
        print2(s[i][5]);
        p[x] = s[i][0];
    }
    return 0;
}

### 关于 SDUT 编译原理 OJ 的 JAVA 题目及解答 #### 行列式的计算 在解决行列式计算问题时,可以采用递归的方式实现。以下是基于 Java 实现的一个简单例子: ```java import java.util.Scanner; public class DeterminantCalculator { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); double[][] matrix = new double[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { matrix[i][j] = scanner.nextDouble(); } } System.out.println(calculateDeterminant(matrix)); } private static double calculateDeterminant(double[][] matrix) { int size = matrix.length; if (size == 1) return matrix[0][0]; // 基础情况 if (size == 2) { // 小矩阵优化 return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]; } double determinant = 0; for (int col = 0; col < size; col++) { double[][] subMatrix = createSubMatrix(matrix, 0, col); // 创建子矩阵 determinant += Math.pow(-1, col) * matrix[0][col] * calculateDeterminant(subMatrix); } return determinant; } private static double[][] createSubMatrix(double[][] original, int excludeRow, int excludeCol) { int size = original.length - 1; double[][] result = new double[size][size]; for (int row = 0, newRow = 0; row < original.length; row++) { if (row != excludeRow) { for (int col = 0, newCol = 0; col < original[row].length; col++) { if (col != excludeCol) { result[newRow][newCol++] = original[row][col]; } } newRow++; } } return result; } } ``` 上述代码实现了通过递归方式求解任意大小方阵的行列式[^1]。 --- #### 异步编程与 Task 处理 对于涉及异步操作的任务处理,在 C# 中可以通过 `Task` 和 `async/await` 来简化复杂逻辑。然而,在 Java 中类似的机制可通过 CompletableFuture 或者线程池来模拟。以下是一个简单的示例展示如何使用 `CompletableFuture` 进行异步任务管理: ```java import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class AsyncExample { public static void main(String[] args) throws ExecutionException, InterruptedException { CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(2000); // 模拟耗时操作 } catch (InterruptedException e) { throw new RuntimeException(e); } return 42; }); Integer result = future.get(); // 获取结果并阻塞当前线程直到完成 System.out.println(result); } } ``` 此代码片段展示了如何利用 `CompletableFuture` 执行后台任务,并等待其执行完毕后再继续主线程的工作流程[^3]。 --- #### JavaScript 初学者指南 虽然本问题是关于 Java 及其相关技术栈的应用场景讨论,但值得一提的是,《JavaScript和jQuery实战手册》也提供了丰富的前端开发技巧。例如,编写第一个 JavaScript 程序通常从基本语法入手,如下所示: ```javascript // 输出 Hello World 至控制台 console.log("Hello World"); // 定义变量并打印到页面 let message = "Welcome to the world of programming!"; document.write(message); ``` 这些基础概念同样适用于理解其他高级特性以及跨平台框架集成的知识体系构建过程[^2]。 --- ### 总结 以上分别介绍了针对行列式计算、异步任务管理和初学阶段脚本语言入门等内容的具体实践案例分析。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值