POJ_2023 Choose Your Own Adventure(DFS)

  /*简单DFS,开始这题想复杂了,不知道用dfs还是bfs甚至都想写dijkstra,后来一狠心
写了个dfs,1Y了,^_^ ,可能题目的数据比较若吧,呵呵,感觉主要还是把图抽出来这地
方,有点像模拟题了。输出是加了一个pre[]存放当前结点的前驱,然后把pre[]包含的结点
信息入栈,然后出栈好了。
*/

//My Code:

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

const int N = 300;
char str[110][N];
int map[110][110];
char res[110][10];
int n;

void display(int now, int pre[]){
//printf("STORY %d\n", ++cas);
int s[110], t, i = 0, j, k;
s[i++] = now;
t = pre[now];
while(t != 1){
s[i++] = t;
t = pre[t];
}
s[i++] = 1;
for(j = i-1; j >= 0; j--){
t = strlen(str[s[j]]);
for(k = 1; k < t-1; k++){
printf("%c", str[s[j]][k]);
}
putchar('\n');
}
}

void dfs(int now, int pre[]){
int flag, i;
for(i = 1; i <= n; i++){
if(map[now][i] == 2){
pre[i] = now;
display(i, pre);
return ;
}
}
for(flag = 0, i = 1; i <= n; i++){
if(map[now][i] == 1){
pre[i] = now;
dfs(i,pre);
}
}
if(!flag) return ;
}

int main(){
//freopen("data.in", "r", stdin);

int t, i, j, x, y, cas = 0;
char c, d;
int pre[110];
scanf("%d", &t);
while(t--){
scanf("%d", &n);
memset(str, 0, sizeof(str));
memset(map, 0, sizeof(map));
memset(res, 0, sizeof(res));
for(i = 1; i <= n; i++){
getchar();
scanf("%c%c", &c, &d);
j = 0;
scanf("%c", &str[i][j++]);
while(1){
scanf("%c", &str[i][j++]);
if(str[i][j-1] == '"')
break;
}
//printf("%c ", c); //puts(str[i]);
if(c == 'C'){
scanf("%d %d", &x, &y);
map[i][x] = map[i][y] = 1;
} else {
scanf("%s", res[i]);
//puts(res[i]);
}
}
for(i = 1; i <= n; i++){
if(res[i][0] == 'H'){
for(j = 1; j <= n; j++){
if(map[j][i] == 1) map[j][i] = 2;
}
}
}
printf("STORY %d\n", ++cas);
memset(pre, 0, sizeof(pre));
dfs(1, pre);
}
return 0;
}



你可能感兴趣的:(poj)