Cod sursa(job #1837898)

Utilizator mark.neaguMark Neagu mark.neagu Data 30 decembrie 2016 16:14:40
Problema Sate Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.57 kb
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

ifstream f("sate.in");
ofstream g("sate.out");

const int NM = 300010;
typedef pair<int, int> PI;

int N, M, X, Y;
vector<PI> G[NM], GI[NM];
int dist[NM];

int main()
{
    f >> N >> M >> X >> Y;
    for (int i=1; i<=M; i++)
    {
        int a, b, c;
        f >> a >> b >> c;
        G[a].push_back(make_pair(b, c));
    }
    
    for (int a=1; a<=N; a++)
    {
        sort(G[a].begin(), G[a].end());
        for (int j = 1; j < G[a].size(); j++)
        {
            int prev = G[a][j - 1].first;
            int now = G[a][j].first;
            G[prev].push_back(make_pair(now, G[a][j].second - G[a][j - 1].second));
        }
        if (G[a].size() > 0)
            GI[G[a][0].first].push_back(make_pair(a, G[a][0].second));
        G[a].clear();
    }
    
    for (int b=N; b>=1; b--)
    {
        sort(GI[b].begin(), GI[b].end(), greater<PI>());
        for (int j = 1; j < GI[b].size(); j++)
        {
            int prev = GI[b][j - 1].first;
            int now = GI[b][j].first;
            GI[prev].push_back(make_pair(now, GI[b][j].second - GI[b][j - 1].second));
        }
        if (GI[b].size() > 0)
            G[GI[b][0].first].push_back(make_pair(b, GI[b][0].second));
        
        dist[b] = 0x3f3f3f3f;
    }
    
    dist[X] = 0;
    for (int i=X; i<=Y; i++)
        for (const auto& it : G[i])
            if (it.first <= Y)
                dist[it.first] = min(dist[it.first], dist[i] + it.second);
    
    g << dist[Y] << '\n';
    
    f.close();
    g.close();
    
    return 0;
}