将定义的变量名进行编号,然后每一个定义中的with后面的变量都是与定义的变量相连,从而构成一个图,用邻接表保存边,用dfs遍历,最后存进去的最先读取,出现过的点均标记,按dfs顺序,把结果存下来。
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <bitset>
#define INF 0x3f3f3f3f
#define eps 1e-6
#define PI 3.1415926
#define mod 1000000007
#define base 2333
using namespace std;
typedef long long LL;
const int inf = 1e9;
const int maxn = 1e5 + 10;
const int maxx = 1e4 + 10;
int n, cnt, len, k, head[maxn], ans[maxn], vis[maxn];
char str[20], val[maxn][20];
map<string, int> mp;
struct node {
int to, next;
} e[maxn<<1];
void add(int from, int to) {
e[len].to = to;
e[len].next = head[from];
head[from] = len++;
}
void dfs(int u) {
vis[u] = 1;
for(int i = head[u]; ~i; i = e[i].next) {
int v = e[i].to;
if(vis[v] == 0)
dfs(v);
}
ans[k++] = u;
}
void solve() {
scanf("%d", &n);
memset(head, -1, sizeof(head));
while(n) {
scanf("%s", str);
if(strcmp(str, "def") == 0) {
scanf("%s", str);
mp[str] = ++cnt;
}
else if(strcmp(str, "with") == 0) {
scanf("%s", str);
add(cnt, mp[str]);
}
else if(strcmp(str, "=") == 0) {
scanf("%s", val[cnt]);
n--;
}
}
scanf("%s", str);
dfs(mp[str]);
for(int i = k-1; i >= 0; i--) {
if(i == 0)
printf("%s\n", val[ans[i]]);
else
printf("%s ", val[ans[i]]);
}
}
int main() {
//srand(time(NULL));
//freopen("kingdom.in","r",stdin);
//freopen("kingdom.out","w",stdout);
solve();
}