您的位置:首页 > 其它

uva 208 Firetruck

2013-10-28 14:42 549 查看
做简单的逆向递归优化后再正向用回溯法进行递归枚举就行了,不进行优化会超时。

#include <stdio.h>
#include <vector>
using namespace std;

bool link_table[30][30];
bool connected[30];
bool visited[30];
vector<int> path;
int path_count;

void clear_link_table()
{
for(int i=1; i<=25; i++)
{
for(int j=1; j<=25; j++)
link_table[i][j] = false;
}
}

void dfs(int cur, int fire_index)
{
if(visited[cur])
return;

if(!connected[cur])
return;

visited[cur] = true;
path.push_back(cur);

if(cur == fire_index)
{
int i;
for(i=0; i<path.size()-1; i++)
printf("%d ", path[i]);
printf("%d\n", path[i]);

vector<int>::iterator it;
it = path.end();
path.erase(--it);
visited[cur] = false;
path_count++;
return;
}

for(int i=1; i<=25; i++)
if(link_table[i][cur])
dfs(i, fire_index);

vector<int>::iterator it;
it = path.end();
path.erase(--it);
visited[cur] = false;
}

void find_connected(int cur)
{
if(!connected[cur])
{
connected[cur] = true;

for(int i=1; i<=25; i++)
if(link_table[i][cur])
find_connected(i);
}
}

void func(int fire_index)
{
int i;

for(i=1; i<=25; i++)
connected[i] = false;

find_connected(fire_index);

for(i=1; i<=25; i++)
visited[i] = false;

path.clear();
path_count = 0;
dfs(1, fire_index);
printf("There are %d routes from the firestation to streetcorner %d.\n", path_count, fire_index);
}

int main(void)
{
int n;
int a, b;
int count;

//freopen("input.dat", "r", stdin);

count = 0;
while(scanf("%d",&n) != EOF)
{
clear_link_table();
while(1)
{
scanf("%d %d", &a, &b);
if(!a && !b)
break;

link_table[a][b] = link_table[b][a] = true;
}
count ++;
printf("CASE %d:\n", count);
func(n);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  uva acm