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

795

被折叠的 条评论
为什么被折叠?



