Gridland Metro

  • + 1 comment
    long gridlandMetro(long n, long m, int k, vector<vector<int>> track) {
        if (track.empty()) return n * m;
        long lamppost = 0;
        sort(track.begin(), track.end());
        int currentRow = track[0][0], trackCell = 0, lastEnd = 0, rowCounter = 1;
        for (int i=0; i < track.size(); i++) {
            if (track[i][0] != currentRow) {
                lamppost = lamppost + m - trackCell;
                currentRow = track[i][0];
                trackCell = 0;
                lastEnd = 0;
                rowCounter++;
            }
            if (i < track.size()-1 and track[i+1][0] == currentRow and track[i][1] == track[i+1][1]) continue;
            trackCell = trackCell + track[i][2] - track[i][1] + 1;
            trackCell = (track[i][1] <= lastEnd) ? (trackCell - min(lastEnd-track[i][1]+1, track[i][2]-track[i][1]+1)) : trackCell;
            lastEnd = max(lastEnd, track[i][2]);
        }
        lamppost = lamppost + m - trackCell + m * (n - rowCounter);
        return lamppost;
    }
    

    O(n) except for the sort line