简单的代码生成程序

来源:互联网 发布:网络系统集成试题 编辑:程序博客网 时间:2024/06/03 18:51

简单的代码生成程序

Time Limit: 1000MSMemory Limit: 65536KB
SubmitStatistic

Problem Description

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

Input

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

Output

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

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

Example Input

4 2T:=A-BU:=A-CV:=T+UW:=V+U

Example Output

LD R0, ASUB R0, BLD R1, ASUB R1, CADD R0, R1ADD R0, R1

代码:

#include <bits/stdc++.h>using namespace std;const int MAXN = 10;int n,m;char s[110][MAXN];char R[MAXN];int cntm;int is_inR(char c){    for(int i = 0; i < m; ++i)if(R[i] == c)return i;    return -1;}int get_uselast(int pos,char c){    for(int i = pos; i < n; ++i)    {        if(s[i][3] == c || s[i][5] == c)return i;    }    return n;}int get_pos(int pos){    if(cntm < m)return cntm++;    int ans = -1,mm = -1;    for(int i = 0; i < m; ++i)    {        int ne = get_uselast(pos,R[i]);        if(ne > mm)mm = ne,ans = i;    }    return ans;}void print_operator(char c){    if(c == '+')printf("ADD");    else if(c == '-')printf("SUB");    else if(c == '*')printf("MUL");    else if(c == '\\')printf("DIV");}void print_right(char c){    int pos = is_inR(c);    if(pos != -1)printf("R%d\n",pos);    else printf("%c\n",c);}int main(){    scanf("%d%d",&n,&m);    cntm = 0;    for(int i = 0; i < n; ++i)scanf("%s",s[i]);    for(int i = 0; i < n; ++i)    {        int pos = is_inR(s[i][3]);        if(pos == -1)        {            pos = get_pos(i);            if(R[pos] && get_uselast(i,R[pos]) < n)printf("ST R%d, %c\n",pos,R[pos]);            printf("LD R%d, %c\n",pos,s[i][3]);        }        print_operator(s[i][4]);        printf(" R%d, ",pos);        print_right(s[i][5]);        R[pos] = s[i][0];    }    return 0;}


原创粉丝点击