uva 208 Firetruck

做简单的逆向递归优化后再正向用回溯法进行递归枚举就行了,不进行优化会超时。

#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);
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值