【DFS】【NOIP2012PJ】文化之旅

本文详细解析了洛谷平台上的P1078题目,采用深度优先搜索(DFS)结合剪枝策略解决路径寻优问题。通过排除已学习文化和被排斥文化的路径,实现从起点到终点的最短路径计算。

L i n k Link Link

l u o g u   P 1078 luogu\ P1078 luogu P1078

D e s c r i p t i o n Description Description

在这里插入图片描述

S a m p l e Sample Sample I n p u t Input Input 1 1 1

2 2 1 1 2 
1 2 
0 1 
1 0 
1 2 10 

S a m p l e Sample Sample O u t p u t Output Output 1 1 1

-1

S a m p l e Sample Sample I n p u t Input Input 2 2 2

2 2 1 1 2 
1 2 
0 1 
0 0 
1 2 10 

S a m p l e Sample Sample O u t p u t Output Output 2 2 2

10

H i n t Hint Hint

在这里插入图片描述

T r a i n Train Train o f of of T h o u g h t Thought Thought

DFS + 剪枝
如果目标点排斥当前点的文化,则不走
如果目标点文化已经学习过,则不走
注意 a i , j = 1 a_{i,j} = 1 ai,j=1是指文化 i i i排斥文化 j j j

C o d e Code Code

#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;

int ans = 1e9, n, m, s, t, k, e, d;
int bb[101], c[101], h[101], a[101][101], b[101];

struct node
{
	int to, next, val;
}w[20001];

void DFS(int s, int now)
{
	b[c[s]] = 1;
	if (s == e) {
		ans = min(now, ans);
		return;
	}
	for (int i = h[s]; i; i = w[i].next)
	{
		int eq = w[i].to;
		if (b[c[eq]]) continue;//对方文化已学习
		if (a[c[eq]][c[s]]) continue;//对方排斥我方
		DFS(eq, now + w[i].val);
	}
	b[s] = 0;
}

int main()
{
	scanf("%d%d%d%d%d", &n, &k, &m, &s, &e);
	for (int i = 1; i <= n; ++i)
		scanf("%d", &c[i]);
	for (int i = 1; i <= k; ++i)
	for (int j = 1; j <= k; ++j)
		scanf("%d", &a[i][j]);
	for (int i = 1; i <= m; ++i)
	{
		int u, v;
		scanf("%d%d%d", &u, &v, &d);
		w[++t] = (node){u, h[v], d}; h[v] = t;
		w[++t] = (node){v, h[u], d}; h[u] = t;
	}//建图
	DFS(s, 0);
	if (ans == 1e9) printf("-1");
		else printf("%d", ans);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值