#include <iostream>
#include <cstring>
#include <set>
#include <queue>
#define x first
#define y second
using namespace std;
typedef pair<int,int> PII;
const int N=150,M=1 << 10;
int h[N],e[M],ne[M],idx,w[M];//w[]门的类型,本题中不为0代表有一种类型的门
int n,m,p,k;
int dx[4]={0,0,1,-1},dy[4]={1,-1,0,0};
int g[N][N],key[M]; //key来存有没有这种钥匙,因为只会有1 ~ 10 这10种钥匙,所以用1111111111(二进制来表示某一种钥匙有没有)
int dist[N][M];
bool st[N][M];
set<PII> edges; //用set来存边的好处:可以用.count(),方法来确定是不是有门/墙了 (PS:墙可以看成没有钥匙的门)
void add(int a,int b,int c)
{
w[idx]=c,e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
void build() //建剩余的边(因为空地并未给出,所以要枚举所有的可能
{
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
for(int k=0;k<4;k++) //各个方向
{
int x = i + dx[k], y = j + dy[k];
if(x>n || x <=0 || y>m || y<=0)continue;
int a=g[i][j],b=g[x][y];
if(edges.count({a,b}) == 0) //set中没有,代表是空地,直接建边
edges.insert({a,b}),add(a,b,0); //这里面的add中的c代表权重
}
}
int bfs()
{
memset(dist,0x3f,sizeof dist);
dist[1][0]=0;//表示在(1,1)点时,没有一把钥匙时的距离为0(初始化)
deque<PII> q;
q.push_back({1,0});
while(q.size())
{
PII t=q.front();
q.pop_front();
if(t.x == n * m)return dist[t.x][t.y]; //第一次查到时即为最短路径(可以理解为当以t.x更新别的边时,永远不可能再让t.x的值变得比当前的t.x小了)
if(st[t.x][t.y])continue;
st[t.x][t.y]=true;
if(key[t.x]) //这里有钥匙的话,t.y代表没拿t.x位置的钥匙前有的钥匙
{
int state = t.y | key[t.x]; //有这种钥匙,就加上这种钥匙
if(dist[t.x][state] > dist[t.x][t.y] + 0) //拿钥匙不消耗时间
{
dist[t.x][state] = dist[t.x][t.y] + 0;
q.push_front({t.x,state}); //边权为0,加到队首
}
}
for(int i=h[t.x]; ~i;i=ne[i])
{
int j=e[i]; //枚举能到的坐标
if(w[i] && !(t.y >> (w[i] - 1) & 1))continue; //有门,且无钥匙,就先跳过
//else 的话,有两种可能 1.有门有钥匙。2.空地随便过。因为是墙的时候,我们根本没用add函数建边,所以墙的情况不会有
if(dist[j][t.y] > dist[t.x][t.y] + 1)
{
dist[j][t.y] = dist[t.x][t.y] + 1;
q.push_back({j, t.y}); // 边权为1,加到队尾
}
}
}
return -1;
}
int main()
{
scanf("%d%d%d%d",&n,&m,&p,&k);
for(int i=1,t=1; i<=n ; i++)
for(int j=1; j<=m ; j++)
g[i][j] = t ++;//将二维坐标一维化
memset(h,-1,sizeof h);
while(k --)
{
int x1,y1,x2,y2,c;
scanf("%d%d%d%d%d",&x1,&y1,&x2,&y2,&c);
int a=g[x1][y1],b=g[x2][y2];
edges.insert({a,b}),edges.insert({b,a});//注意是双向,可能是
if(c)add(a,b,c),add(b,a,c); // 如果是门的话,才用邻接表建边
}
build();
int s;
scanf("%d",&s);
while(s --)
{
int x,y,id;
scanf("%d%d%d",&x,&y,&id);
key[g[x][y]] |= 1 << id - 1;
}
cout<<bfs();
//yxc 真大佬,厉害!
return 0;
}