UVA 10557 - XYZZY

本文深入探讨了深度优先搜索(DFS)算法的应用场景和技术要点,特别是在处理节点重复进入及环的情况时的处理策略。通过一个具体的实战案例,展示了如何利用DFS解决实际问题,并提供了完整的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 这题用的是DFS , 有的麻烦 。

要点:结点可以重复进入,需要处理环的情况。


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <queue>
#include <utility>
#include <tuple>
#include <algorithm>
#include <ctime>

using namespace std;

const int size = 100 + 10;

int w[size];
int m[size][size][2];

int v[size] , v2[size];
int now[size] , st[size];
int aa[size];

int dfs2(int x , int y)
{
	if(x == y) return 1;
	v2[x] = 1;
	for(int i = m[x][0][1] ; i ; i = m[x][i][1])
	{
		int tx = m[x][i][0];
		if(v2[tx]) continue;
		if(dfs2(tx , y)) return 1;
	}
	return 0;
}

int dfs(int x , int y , int cost , int cur)
{
	if(x == y) return 1;
	if(!st[x]) return 0;

	for(int i = m[x][0][1] ; i ; i = m[x][i][1])
	{
		int tx = m[x][i][0];
		int tcost = cost + w[tx];
		if(tcost <= now[tx] || st[tx] == 0) continue;
		if(find(aa , aa+cur , tx) != (aa+cur)) return 1;
		now[tx] = tcost; aa[cur+1] = tx;
		if(dfs(tx , y , tcost , cur+1)) return 1;
	}
	return 0;
}

int main()
{
	int n;
	while(cin >> n && n != -1)
	{
		for(int i = 0 ; i < n ; ++i)
		{
			cin >> w[i];
			int t;
			cin >> t;
			m[i][0][1] = 0;
			for(int j = 1 ; j <= t ; ++j)
			{
				int r;
				cin >> r;
				m[i][j][0] = r - 1;
				m[i][j-1][1] = j;
			}
			m[i][t][1] = 0;
		}
		
		for(int i = 0 ; i < n ; ++i)
		{
			memset(v2 , 0 , sizeof(v2));
			st[i] = dfs2(i , n - 1);
		}
		
		memset(v , 0 , sizeof(v));
		memset(now , 0 , sizeof(now));
		v[0] = 1; now[0] = 100; 
		if(!dfs(0 , n-1 , 100 , 0)) cout << "hopeless" << endl;
		else cout << "winnable" << endl;
	}	
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值