【SPFA】【最短路】【CSP-J T4】加工零件

L i n k Link

l u o g u luogu P 5663 P5663

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

在这里插入图片描述

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

3 2 6
1 2
2 3
1 1
2 1
3 1
1 2
2 2
3 2

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

No
Yes
No
Yes
No
Yes

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

5 5 5
1 2
2 3
3 4
4 5
1 5
1 1
1 2
1 3
1 4
1 5

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

No
Yes
No
Yes
Yes

H i n t Hint

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

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

这道题通过思考可以转换为:从 a a 点出发,走 L L 步是否能走到 1 1
然后又可以发现,若走 L L 步能到 1 1 点,那么,走到与 1 1 连接的点,滚多几遍,也还是可以回到 1 1 点,因此,得出结论:
a a 点出发走 L L 步能到 1 1 点,那么走 L + 2 L + 2 , L + 4 L + 4 …都是可行的。
所以。。。要打最短路,然后判断奇偶性
又因为。。。如果图里面有环,那么奇偶的可能性都有,所以求最短路时要奇偶都求

C o d e Code

#include<cstring>
#include<iostream>
#include<cstdio>
#include<queue>

using namespace std;

struct Node
{
	int u, v;
}node[200005];

int n, m, q, t, h[200005], c[100005][2];

void SPFA(int x)
{
	memset(c, 0x7f, sizeof(c));
	queue<int>Q;
	c[1][0] = 0;
	Q.push(1);
	while (Q.size())
	{
		int f = Q.front();
		Q.pop();
		for (int i = h[f]; i; i = node[i].v)
		{
			int tt = node[i].u;
			if (c[f][0] + 1 < c[tt][1])
			{
				c[tt][1] = c[f][0] + 1;
				Q.push(tt);
			}//求奇数
			if (c[f][1] + 1 < c[tt][0])
			{
				c[tt][0] = c[f][1] + 1;
				Q.push(tt); 
			}//求偶数
			//这里少了一句判断还能A很是奇妙
		}
	}
}

int main()
{
	scanf("%d%d%d", &n, &m, &q);
	for (int i = 1; i <= m; ++i)
	{
		int u, v;
		scanf("%d%d", &u, &v);
		node[++t] = (Node) {v, h[u]}; h[u] = t;
		node[++t] = (Node) {u, h[v]}; h[v] = t;//建图
	}
	SPFA(1);
	for (int i = 1; i <= q; ++i)
	{
		int a, l;
		scanf("%d%d", &a, &l);
		if (c[a][l % 2] <= l) printf("Yes\n");
		 else printf("No\n");
	}
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/LTH060226/article/details/103408728
今日推荐