#include #include #include #include using namespace std; const int INF = 1e9; struct Edge { int to, cost, time; Edge(int t, int c, int tm) : to(t), cost(c), time(tm) {} }; int main() { ios_base::sync_with_stdio(false); cin.tie(0); int N, C, V; cin >> N >> C >> V; // Read input directly into separate vectors vector S(V), T(V), Y(V), M(V); for (int i = 0; i < V; i++) cin >> S[i]; for (int i = 0; i < V; i++) cin >> T[i]; for (int i = 0; i < V; i++) cin >> Y[i]; for (int i = 0; i < V; i++) cin >> M[i]; // Build graph with move semantics for edges vector> graph(N); for (int i = 0; i < V; i++) { graph[S[i] - 1].emplace_back(T[i] - 1, Y[i], M[i]); } // Use move semantics to optimize memory for large cases vector> dp; dp.reserve(N); for (int i = 0; i < N; i++) { // Construct each row in place dp.emplace_back(C + 1, INF); } dp[0][C] = 0; // Main DP loop with reference optimization for (int i = 0; i < N; i++) { auto& edges = graph[i]; // Reference to avoid copy auto& dp_row = dp[i]; // Reference to current dp row for (int k = C; k >= 0; k--) { if (dp_row[k] == INF) continue; for (const auto& edge : edges) { if (k >= edge.cost) { auto& target_row = dp[edge.to]; int new_time = dp_row[k] + edge.time; if (new_time < target_row[k - edge.cost]) { target_row[k - edge.cost] = new_time; } } } } } // Calculate result int result = INF; for (int k = 0; k <= C; k++) { result = min(result, dp[N - 1][k]); } cout << (result == INF ? -1 : result) << endl; return 0; }