This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#include "garden.h"
#include "gardenlib.h"
using namespace std;
const int mxn = 1.5e5 + 1000;
const int MXN = 3e5 + 100000;
typedef pair<int, int> pii;
#define ff first
#define ss second
#define MP make_pair
vector<int> adj[mxn]; // OG graph
vector<int> rev[MXN]; // buba graph
int nxt[MXN];
bool vis[MXN];
bool fake(int cur, int prv) {
if(adj[cur].size() == 1) return 0;
return prv == adj[cur][0];
}
void build_buba(int cur, int prv = -1) {
int bu = cur + mxn * fake(cur, prv);
if(vis[bu]) return;
vis[bu] = 1;
int sus = 0;
if(adj[cur].size() == 1) sus = adj[cur][0];
else if(prv == adj[cur][0]) sus = adj[cur][1];
else sus = adj[cur][0];
int bv = sus + mxn * fake(sus, cur);
nxt[bu] = bv;
rev[bv].push_back(bu);
build_buba(sus, cur);
}
vector<int> dis(MXN, -1);
vector<int> fdis(MXN, -1);
void bfs(int P, vector<int> &dis) {
priority_queue<pii> pq;
pq.push(MP(0, P));
while(pq.size()) {
int d = -pq.top().ff;
int u = pq.top().ss;
pq.pop();
if(dis[u] > -1) continue;
dis[u] = d;
for(int v : rev[u])
if(dis[v] == -1)
pq.push(MP(-d-1, v));
}
}
int cyc(int P) {
for(int i = 0; i < MXN; i++)
vis[i] = 0;
int cur = P, cnt = 0;
vector<int> path;
while(!vis[cur]) {
vis[cur] = 1;
path.push_back(cur);
cur = nxt[cur];
}
while(path.back() != cur) {
path.pop_back();
cnt++;
}
if(cur != P) return 0;
return cnt + 1;
}
void count_routes(int N, int M, int P, int R[][2], int Q, int G[]) {
for(int i = 0; i < M; i++) {
int u = R[i][0];
int v = R[i][1];
adj[u].push_back(v);
adj[v].push_back(u);
}
memset(nxt, -1, sizeof nxt);
for(int i = 0; i < N; i++)
build_buba(i, -1);
memset(vis, 0, sizeof vis);
int in1 = cyc(P);
int in2 = cyc(P + mxn);
bfs(P, dis);
bfs(P + mxn, fdis);
auto sus1 = [&] (int u, int D) -> bool {
if(dis[u] == -1) return 0;
if(dis[u] == D) return 1;
if(dis[u] > D) return 0;
return in1 && ((D - dis[u]) % in1 == 0);
};
auto sus2 = [&] (int u, int D) -> bool {
if(fdis[u] == -1) return 0;
if(fdis[u] == D) return 1;
if(fdis[u] > D) return 0;
return in2 && ((D - fdis[u]) % in2 == 0);
};
for(int i = 0; i < Q; i++) {
int D = G[i], ans = 0;
for(int u = 0; u < N; u++) {
if(sus1(u, D) || sus2(u, D)) {
ans++;
}
}
answer(ans);
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |