当年现场赛没人能做出来。受高人指点过掉。
#include <stdio.h>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
#define SZ(V) ((int)((V).size()))
#define MX_N 100001
vector<int> edge[MX_N];
vector<pair<int, int> > ed[MX_N];
int N, M, Q;
int sp[MX_N];
int dep[MX_N];
int st[MX_N], en[MX_N];
const int slMX = 100000000;
int sol[slMX], sl;
int stx[MX_N], stackd[MX_N], sti[MX_N], sth;
void push(int x,int d) {
stx[sth] = x;
stackd[sth] = d;
sti[sth] = 0;
sth ++;
}
void back(int x, int d) {
sth = 0;
push(x,d);
while(sth > 0) {
int x = stx[sth-1];
int d = stackd[sth-1];
int i = sti[sth-1];
sti[sth-1] ++;
if (sl >= slMX) return;
if (i == 0) {
dep[x] = d;
st[x] = sl;
if (sp[x]) {
sol[sl] = d;
sl ++;
if (sl >= slMX) return;
}
}
if (i >= SZ(edge[x]))
{
en[x] = sl;
sth --;
continue;
}
int u = edge[x][i];
if (dep[u] == 0) {
push(u, d+1);
} else {
int pldep = d+1 - dep[u];
for (int v=st[u]; v < en[u]; v++) {
sol[sl] = sol[v] + pldep;
sl ++;
if (sl >= slMX) return;
}
}
}
}
int main() {
int T;
scanf("%d",&T);
while(T-->0) {
scanf("%d %d %d",&N,&M,&Q);
for (int i=1;i<N;i++) {
scanf("%d",&sp[i]);
}
for (int i=0;i<M;i++) {
int u, v, w;
scanf("%d %d %d", &u,&v,&w);
u--;v--;
ed[u].push_back( make_pair(w, v) );
}
for (int i=0;i<N;i++) {
sort(ed[i].begin(), ed[i].end());
for (int j=0;j<SZ(ed[i]);j++ ){
edge[i].push_back(ed[i][j].second);
}
}
sl = 0;
back(0, 1);
for (int i=0;i<N;i++) {
ed[i].clear();
edge[i].clear();
sp[i] = 0;
dep[i] = 0;
}
static int cs = 1;
printf("Case #%d:\n", cs);
cs ++;
for (int i=0;i<Q;i++) {
int q;
scanf("%d",&q);
if (q > sl) printf("-1\n");
else printf("%d\n", sol[q-1]-1);
}
}
return 0;
}