图是强联通图,因此对于两点 有路径 和 。
考虑我们连额外边的时候,
如图上,因为 之间一定有路径, 之间一定有路径所以此时一定会形成一个环。
怎样快速判断?首先想一下如何快速确定两点之间距离。
- 距离 才有用。
- 考虑固定一个点(比如 号点),一对
如图上,可以得出 。
设 为 。
接下来,可以就可以得出对于第一个图,要求为:
那么也就是说,所有的两个图间建的同向边 有 相等。
设 ,那么 。
统计数组 , 表示有多少个 。
可以同时算出 。
然后对其做哈希匹配。
对于一对需要形如 匹配的 ,需要满足:
也就是说在 固定的时候对于 的每一个值(设为 )有图一 的个数等于图二 的个数。
所以应该是把 右移 次和 做匹配。对于两个方向的边都是这样,因为对称, 可以直接推出。
#include<bits/stdc++.h>
#define ull unsigned long long
#define ul unsigned int
using namespace std;
const int N = 200010;
const ul bs = 13331;
int n, k, tp[2][N], w[2][N], cnt[2][2][N];
vector <int> g[2][N];
bool vis[N];
struct node{
ull a;ul b;
bool operator == (const node &s)const{
return (a == s.a) && (b == s.b);
}
node operator * (const ul &v)const{
return {a * v, b * v};
}
node operator * (const node &s)const{
return {a * s.a, b * s.b};
}
node operator + (const node &s)const{
return {a + s.a, b + s.b};
}
node operator + (const ul &v)const{
return {a + v, b + v};
}
node operator - (const node &s)const{
return {a - s.a, b - s.b};
}
}h[2][2][N], mi[N];
void bfs(bool t){
queue <int> q;
for(int i = 1;i <= n;i++){
vis[i] = 0;
}
vis[1] = 1;
q.push(1);
while(!q.empty()){
int p = q.front();
q.pop();
for(auto x : g[t][p]){
if(vis[x])continue;
w[t][x] = (w[t][p] + 1) % k;
q.push(x);vis[x] = 1;
}
}
for(int i = 1;i <= n;i++){
cnt[t][tp[t][i]][w[t][i]]++;
}
}
node get_v(bool t0, bool t1, int x){
// x 在前
node v0 = h[t0][t1][k] - h[t0][t1][k - x] * mi[x];
// k - x 在后
node v1 = h[t0][t1][k - x];
return (v0 * mi[k - x] + v1);
}
void solve(){
scanf("%d%d", &n, &k);
for(int j = 0;j <= 1;j++){
for(int i = 1;i <= n;i++){
scanf("%d", &tp[j][i]);
w[j][i] = 0, cnt[j][0][i - 1] = 0, cnt[j][1][i - 1] = 0;
g[j][i].clear();
}
int m;
scanf("%d", &m);
for(int i = 1;i <= m;i++){
int x, y;
scanf("%d%d", &x, &y);
g[j][x].push_back(y);
}
bfs(j);
}
int tmp0 = 0, tmp1 = 0;
for(int i = 1;i <= n;i++){
tmp0 += (int)tp[0][i];
tmp1 += (int)tp[1][i];
}
if(tmp0 + tmp1 != n){
printf("NO\n");
return;
}
if(tmp0 == 0 || tmp0 == n){
printf("YES\n");
return;
}
for(int j0 = 0;j0 <= 1;j0++){
for(int j1 = 0;j1 <= 1;j1++){
for(int i = 1;i <= k;i++){
ul v = cnt[j0][j1][i - 1];
h[j0][j1][i] = h[j0][j1][i - 1] * bs + v;
// printf("%d ", h[j0][j1][i].b);
}
// printf("\n");
}
// printf("\n");
}
for(int t0 = 0; t0 < k; t0++){
int t1 = ((-2 - t0) % k + k) % k;
// printf("%d %d\n", t0, t1);
// 图2 outgoing -> 图1 incoming
bool ok0 = (h[1][1][k] == get_v(0, 0, t0));
// 图1 outgoing -> 图2 incoming
bool ok1 = (h[0][1][k] == get_v(1, 0, t1));
if(ok0 && ok1){
printf("YES\n");
return;
}
}
printf("NO\n");
}
void init(){
mi[0] = {1, 1};
for(int i = 1;i <= N - 5;i++){
mi[i] = mi[i - 1] * bs;
}
}
int main(){
int t;init();
scanf("%d", &t);
while(t--){
solve();
}
return 0;
}

