P - 简单的代码生成程序
Description
通过三地址代码序列生成计算机的目标代码,在生成算法中,对寄存器的使用顺序为:寄存器中存有 > 空寄存器 > 内存中存有 > 以后不再使用 > 最远距离使用
Input
单组输入,给定输出的三地址代码的个数和寄存器的个数.所有的变量为大写字母,寄存器的数量不超过9
Output
参照示例格式输出,不需要将最后的寄存器中的值写回内存
不再使用变量不用写回内存
Sample
Input
4 2
T:=A-B
U:=A-C
V:=T+U
W:=V+U
Output
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;
char p[100];
char s[100][100];
int n, m ,q= 0;
int g(char c)
{
for(int i = 0; i < m; i++)
{
if(c == p[i]) return i;
}
return -1;
}
int u(int x, char c)
{
for(int i = x; i < n; i++)
{
if(c == s[i][3] || c== s[i][5]) return i;
}
return n;
}
int f(int x)
{
if(q < m) return q++;
int a=-1,t = -1;
for(int i = 0; i < m; i++)
{
int k = u(x, p[i]);
if(k > a)
{
a = k;
t = i;
}
}
return t;
}
int main()
{
cin>>n>>m;
for(int i = 0; i < n; i++)
cin>>s[i];
for(int i = 0; i < n; i++)
{
int x = g(s[i][3]);
if(x == -1)
{
x = f(i);
if(p[x] != '\0' && u(i, p[x]) < n)
{
printf("ST R%d, %c\n", x, p[x]);
p[x] = NULL;
}
printf("LD R%d, %c\n", x, s[i][3]);
}
char c=s[i][4];
if(c == '+') printf("ADD ");
else if(c == '-') printf("SUB ");
else if(c == '*') printf("MUL ");
else if(c == '\\') printf("DIV ");
printf("R%d, ", x);
int b = g(s[i][5]);
if(b != -1) printf("R%d\n", b);
else printf("%c\n", s[i][5]);
p[x] = s[i][0];
}
return 0;
}