Cod sursa(job #1942354)

Utilizator failureJust a Joke failure Data 27 martie 2017 22:21:23
Problema Amenzi Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.39 kb
#include <bits/stdc++.h>

#define MAXN 151
#define MAXT 3501
#define MAXQ 8001

using namespace std;

vector <pair <int, int> > G[MAXN];
deque <pair <int, int> > Q;

pair <int, int> query[MAXQ];

int n, m, k, p, maxT, d[MAXN][MAXT], value[MAXN][MAXT];
bool inq[MAXN][MAXT], seen[MAXN][MAXT];

void bellmanford()
{
    int i;
    pair <int, int> node, son;

    while(!Q.empty()) {
        node = Q.front();
        inq[node.first][node.second] = 0;
        seen[node.first][node.second] = 1;
        Q.pop_front();
        for(i=0; i<G[node.first].size(); ++i) {
            son.first = G[node.first][i].first; //neighbour
            son.second = node.second + G[node.first][i].second; //time
            if(son.second > maxT) continue;
            if(d[son.first][son.second] < d[node.first][node.second] + value[son.first][son.second]) {
                d[son.first][son.second] = d[node.first][node.second] + value[son.first][son.second];
                if(!inq[son.first][son.second]) {
                    Q.push_back(son);
                    inq[son.first][son.second] = 1;
                }
            }
        }

        son.first = node.first;
        son.second = node.second + 1;
        if(son.second > maxT) continue;
        if(d[son.first][son.second] < d[node.first][node.second] + value[son.first][son.second]) {
            d[son.first][son.second] = d[node.first][node.second] + value[son.first][son.second];
            if(!inq[son.first][son.second]) {
                Q.push_back(son);
                inq[son.first][son.second] = 1;
            }
        }
    }
}

int main()
{
    freopen("amenzi.in", "r", stdin);
    freopen("amenzi.out", "w", stdout);

    int x, y, z, i;

    scanf("%d%d%d%d", &n, &m, &k, &p);
    for(i=1; i<=m; ++i) {
        scanf("%d%d%d", &x, &y, &z);
        G[x].push_back({y, z});
        G[y].push_back({x, z});
    }

    for(i=1; i<=k; ++i) {
        scanf("%d%d%d", &x, &y, &z);
        value[x][y] = z;
    }

    for(i=1; i<=p; ++i) {
        scanf("%d%d", &query[i].first, &query[i].second);
        maxT = max(maxT, query[i].second);
    }

    Q.push_back({1, 0});
    inq[1][0] = 1;

    bellmanford();

    for(i=1; i<=p; ++i) {
        x = query[i].first;
        y = query[i].second;
        if(!seen[x][y]) printf("-1\n");
        else printf("%d\n", d[x][y]);
    }

    return 0;
}