Search is not available for this dataset
name
stringlengths 2
112
| description
stringlengths 29
13k
| source
int64 1
7
| difficulty
int64 0
25
| solution
stringlengths 7
983k
| language
stringclasses 4
values |
---|---|---|---|---|---|
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using pil = pair<int, ll>;
using pli = pair<ll, int>;
using piii = pair<int, pii>;
using plll = pair<ll, pll>;
using pib = pair<int, bool>;
using pdi = pair<double, int>;
using pid = pair<int, double>;
using ld = long double;
using piiii = pair<pii, pii>;
bool cmp(piiii &p1, piiii &p2) {
if (p1.first.first == p2.first.first) {
return p1.second.second < p2.second.second;
}
return p1.first.first < p2.first.first;
}
int n, m, k, a, b, c, d, cost[100001];
bool v[100001];
vector<piiii> v1, v2;
stack<piiii> stk[100001];
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> m >> k;
for (int i = 0; i < m; i++) {
cin >> a >> b >> c >> d;
if (b == 0) {
v2.push_back({{a, b}, {c, d}});
} else {
v1.push_back({{a, b}, {c, d}});
}
}
sort(v1.begin(), v1.end());
sort(v2.begin(), v2.end());
ll t1 = 0;
int cnt = 0;
ll t2 = 0;
for (int i = v2.size() - 1; i >= 0; i--) {
if (stk[v2[i].second.first].empty()) t2++;
if (stk[v2[i].second.first].empty() ||
v2[i].second.second < stk[v2[i].second.first].top().second.second)
stk[v2[i].second.first].push(v2[i]);
else
v[i] = true;
}
if (t2 != n) {
cout << -1 << "\n";
return 0;
}
t2 = 0;
for (int i = 1; i <= n; i++) {
t2 += stk[i].top().second.second;
}
ll ans = 0x3f3f3f3f3f;
bool first = true;
int idx = 0;
for (int i = 0; i < v1.size(); i++) {
if (cost[v1[i].first.second] == 0) cnt++;
if (cost[v1[i].first.second] == 0 ||
cost[v1[i].first.second] > v1[i].second.second) {
t1 += v1[i].second.second - cost[v1[i].first.second];
cost[v1[i].first.second] = v1[i].second.second;
} else
continue;
while (v2[idx].first.first - v1[i].first.first <= k) {
if (v[idx]) {
idx++;
continue;
}
if (stk[v2[idx].second.first].size() == 1) {
first = false;
break;
}
piiii p = stk[v2[idx].second.first].top();
stk[v2[idx].second.first].pop();
t2 -= p.second.second - stk[v2[idx].second.first].top().second.second;
idx++;
}
if (!first) break;
if (cnt == n) {
ans = min(ans, t1 + t2);
}
}
if (ans == 0x3f3f3f3f3f) {
cout << -1 << "\n";
} else {
cout << ans << "\n";
}
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | import java.io.*;
import java.math.*;
import java.util.*;
public class CODEFORCES
{
private InputStream is;
private PrintWriter out;
public static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
public static class Pair implements Comparable<Pair>
{
long u, v;
public Pair(int u, int v)
{
this.u = u;
this.v = v;
}
public int hashCode()
{
int hu = (int) (u ^ (u >>> 32));
int hv = (int) (v ^ (v >>> 32));
return 31 * hu + hv;
}
public boolean equals(Object o)
{
Pair other = (Pair) o;
return u == other.u && v == other.v;
}
public int compareTo(Pair other)
{
return Long.compare(u, other.u) != 0 ? Long.compare(u, other.u) : Long.compare(v, other.v);
}
public String toString()
{
return u + " " + v;
}
}
void solve()
{
int n = ni(), m = ni(), k = ni();
ArrayList<Pair> inc[] = new ArrayList[1000001];
ArrayList<Pair> dec[] = new ArrayList[1000001];
for (int i = 0; i < 1000001; i++)
{
inc[i] = new ArrayList<Pair>();
dec[i] = new ArrayList<Pair>();
}
while (m-- > 0)
{
int id = ni();
int d = ni(), f = ni(), c = ni();
if (f == 0)
inc[id].add(new Pair(c, d));
else
dec[id].add(new Pair(c, f));
}
for (int i = 0; i <= 1000000; i++)
{
Collections.sort(inc[i]);
Collections.sort(dec[i]);
}
long in[] = new long[n + 1];
long de[] = new long[n + 1];
Arrays.fill(in, Integer.MAX_VALUE);
Arrays.fill(de, Integer.MAX_VALUE);
long it[] = new long[1000001];
long dt[] = new long[1000001];
Arrays.fill(it, (long) 1e16);
Arrays.fill(dt, (long) 1e16);
long mx = 0;
int nm = 0;
for (int i = 0; i <= 1000000; i++)
{
for (Pair j : inc[i])
{
int ind = (int) j.v;
if (in[ind] == Integer.MAX_VALUE)
{
nm++;
mx += j.u;
in[ind] = j.u;
} else if (in[ind] > j.u)
{
mx += j.u - in[ind];
in[ind] = j.u;
}
}
if (nm == n)
it[i] = mx;
}
mx = 0;
nm = 0;
for (int i = 1000000; i >= 0; i--)
{
for (Pair j : dec[i])
{
int ind = (int) j.v;
if (de[ind] == Integer.MAX_VALUE)
{
nm++;
mx += j.u;
de[ind] = j.u;
} else if (de[ind] > j.u)
{
mx += j.u - de[ind];
de[ind] = j.u;
}
}
if (nm == n)
dt[i] = mx;
}
long ans = (long) 1e16;
for (int i = 1; i <= 1000000 - k - 1; i++)
{
long tmp = it[i] + dt[i + k + 1];
ans = Math.min(ans, tmp);
}
if (ans == 1e16)
out.println("-1");
else
out.println(ans);
}
void soln() throws Exception
{
is = System.in;
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception
{
new CODEFORCES().soln();
}
// To Get Input
// Some Buffer Methods
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf)
{
ptrbuf = 0;
try
{
lenbuf = is.read(inbuf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c)
{
return !(c >= 33 && c <= 126);
}
private int skip()
{
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
private double nd()
{
return Double.parseDouble(ns());
}
private char nc()
{
return (char) skip();
}
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b)))
{ // when nextLine, (isSpaceChar(b) && b != '
// ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b)))
{
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-')
{
minus = true;
b = readByte();
}
while (true)
{
if (b >= '0' && b <= '9')
{
num = num * 10 + (b - '0');
} else
{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-')
{
minus = true;
b = readByte();
}
while (true)
{
if (b >= '0' && b <= '9')
{
num = num * 10 + (b - '0');
} else
{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o)
{
if (!oj)
System.out.println(Arrays.deepToString(o));
}
} | JAVA |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int n, m, k, d[100001], f[100001], t[100001], c[100001], I[100001];
inline int Min(int x, int y) { return x < y ? x : y; }
inline long long Min(long long x, long long y) { return x < y ? x : y; }
inline bool cmp(int p1, int p2) { return d[p1] < d[p2]; }
int Dep[100001], Depnum, Arr[100001], Arrnum;
int Minmeet = -1, Maxmeet = -1, Mini, Maxi;
int CityD[100001], CityA[100001];
long long MinDC[100001], MinAC[100001], Ans = 9999999999999999ll;
void init() {
scanf("%d%d%d", &n, &m, &k);
for (int i = 1; i <= m; ++i)
scanf("%d%d%d%d", d + i, f + i, t + i, c + i), I[i] = i;
sort(I + 1, I + m + 1, cmp);
}
int main() {
init();
for (int i = 1; i <= m; ++i) {
if (t[I[i]] == 0) {
CityD[f[I[i]]] = Min(CityD[f[I[i]]], c[I[i]]);
if (!Dep[f[I[i]]]) CityD[f[I[i]]] = c[I[i]], Dep[f[I[i]]] = 1, ++Depnum;
}
if (Depnum == n) {
Minmeet = d[I[i]] + 1;
Mini = i;
break;
}
}
for (int i = m; i >= 1; --i) {
if (f[I[i]] == 0) {
CityA[t[I[i]]] = Min(CityA[t[I[i]]], c[I[i]]);
if (!Arr[t[I[i]]]) CityA[t[I[i]]] = c[I[i]], Arr[t[I[i]]] = 1, ++Arrnum;
}
if (Arrnum == n) {
Maxmeet = d[I[i]] - 1;
Maxi = i;
break;
}
}
if (Minmeet == -1 || Maxmeet == -1 || Maxmeet - Minmeet + 1 < k) {
puts("-1");
return 0;
}
for (int i = 1; i <= n; ++i) MinDC[Mini] += CityD[i];
for (int i = 1; i <= n; ++i) MinAC[Maxi] += CityA[i];
for (int i = Mini + 1; i <= m; ++i) {
MinDC[i] = MinDC[i - 1];
if (t[I[i]] == 0)
if (CityD[f[I[i]]] > c[I[i]])
MinDC[i] -= CityD[f[I[i]]] - c[I[i]], CityD[f[I[i]]] = c[I[i]];
}
for (int i = Maxi - 1; i >= 1; --i) {
MinAC[i] = MinAC[i + 1];
if (f[I[i]] == 0)
if (CityA[t[I[i]]] > c[I[i]])
MinAC[i] -= CityA[t[I[i]]] - c[I[i]], CityA[t[I[i]]] = c[I[i]];
}
for (int i = Mini, j = Mini; i <= Maxi && j <= Maxi; ++i) {
while (j <= Maxi && d[I[j]] - d[I[i]] - 1 < k) ++j;
if (j > Maxi) break;
Ans = Min(Ans, MinDC[i] + MinAC[j]);
}
cout << Ans;
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
struct A {
int d, f, t, c;
bool operator<(const A& a) const { return d < a.d; }
};
A v[100005];
int bestLef[100005], bestRig[100005], nxt[100005], pos[100005];
int main() {
int n, m, k;
cin >> n >> m >> k;
for (int i = 1; i <= m; ++i) cin >> v[i].d >> v[i].f >> v[i].t >> v[i].c;
sort(v + 1, v + m + 1);
int p = 0;
int bad = n;
while (p + 1 <= m && bad) {
p++;
if (v[p].t == 0) {
if (bestLef[v[p].f] == 0) {
bad--;
bestLef[v[p].f] = v[p].c;
} else
bestLef[v[p].f] = min(bestLef[v[p].f], v[p].c);
}
}
if (bad) {
cout << "-1";
return 0;
}
int q = m + 1;
bad = n;
while (q - 1 > 0 && bad) {
q--;
if (v[q].f == 0) {
if (bestRig[v[q].t] == 0) {
bad--;
bestRig[v[q].t] = v[q].c;
} else
bestRig[v[q].t] = min(bestRig[v[q].t], v[q].c);
}
}
if (bad || v[q].d - v[p].d - 1 < k) {
cout << "-1";
return 0;
}
while (v[q - 1].d - v[p].d - 1 >= k) {
--q;
if (v[q].f == 0) bestRig[v[q].t] = min(bestRig[v[q].t], v[q].c);
}
for (int i = m; i; --i) {
if (v[i].f != 0) continue;
nxt[i] = pos[v[i].t];
if (pos[v[i].t] == 0 || v[i].c < v[pos[v[i].t]].c) pos[v[i].t] = i;
}
long long costl = 0, costr = 0;
for (int i = 1; i <= n; ++i) costl += bestLef[i], costr += bestRig[i];
long long sol = costl + costr;
while (q <= m) {
++p;
if (v[p].t == 0) {
costl -= bestLef[v[p].f];
bestLef[v[p].f] = min(bestLef[v[p].f], v[p].c);
costl += bestLef[v[p].f];
}
while (q <= m && v[q].d - v[p].d - 1 < k) {
if (v[q].f == 0) {
costr -= bestRig[v[q].t];
bestRig[v[q].t] = v[nxt[q]].c;
costr += bestRig[v[q].t];
if (nxt[q] == 0) {
q = m + 1;
break;
}
}
q++;
}
if (q > m) break;
sol = min(sol, costl + costr);
}
cout << sol;
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
inline void read(long long &x) {
char c = getchar();
x = 0;
while (c > '9' || c < '0') c = getchar();
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = getchar();
}
}
const long long N = 1000005, mxd = 1000000;
const long long inf = 2e11;
long long f0[N], f1[N];
vector<pair<long long, long long> > v0[N], v1[N];
long long mn[N];
long long n, m, K;
long long d, x, y, z;
long long ans;
signed main() {
read(n);
read(m);
read(K);
for (long long i = 1; i <= m; ++i) {
read(d);
read(x);
read(y);
read(z);
if (y == 0)
v0[d].push_back(make_pair(x, z));
else
v1[d].push_back(make_pair(y, z));
}
for (long long i = 1; i <= n; ++i) mn[i] = inf;
f0[0] = inf * n;
for (long long i = 1; i <= mxd; ++i) {
f0[i] = f0[i - 1];
for (unsigned j = 0; j < v0[i].size(); ++j)
if (mn[v0[i][j].first] > v0[i][j].second) {
f0[i] -= mn[v0[i][j].first] - v0[i][j].second;
mn[v0[i][j].first] = v0[i][j].second;
}
}
for (long long i = 1; i <= n; ++i) mn[i] = inf;
f1[mxd + 1] = inf * n;
for (long long i = mxd; i; --i) {
f1[i] = f1[i + 1];
for (unsigned j = 0; j < v1[i].size(); ++j)
if (mn[v1[i][j].first] > v1[i][j].second) {
f1[i] -= mn[v1[i][j].first] - v1[i][j].second;
mn[v1[i][j].first] = v1[i][j].second;
}
}
ans = inf * n * 2;
for (long long i = 1; i + K + 1 <= mxd; ++i)
ans = min(ans, f0[i] + f1[i + 1 + K]);
if (ans > inf)
puts("-1");
else
cout << ans;
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
inline int mini(int a, int b) { return (a > b) ? b : a; }
inline int maxi(int a, int b) { return (a < b) ? b : a; }
vector<pair<int, int> > to[100010], bak[100010];
int tos[100010], bas[100010];
long long pre[1000010], suf[1000010];
int ear, lat = 100000000;
int main(void) {
int n, m, k;
scanf("%d%d%d", &n, &m, &k);
for (int i = 1; i <= m; i++) {
int tt, ff, dd, cc;
scanf("%d%d%d%d", &tt, &ff, &dd, &cc);
if (ff) {
to[ff].push_back(make_pair(tt, cc));
} else {
bak[dd].push_back(make_pair(tt, cc));
}
}
for (int i = 1; i <= n; i++) {
sort(to[i].begin(), to[i].end());
sort(bak[i].begin(), bak[i].end());
tos[i] = to[i].size();
bas[i] = bak[i].size();
if (to[i].empty() || bak[i].empty()) {
printf("-1");
return 0;
}
ear = maxi(ear, to[i][0].first + 1);
lat = mini(lat, bak[i][bas[i] - 1].first - k);
}
if (ear > lat) {
printf("-1");
return 0;
}
for (int i = 1; i <= n; i++) {
int mn = 10000000;
int j = 0;
while (j < tos[i] && to[i][j].first < ear) {
mn = mini(mn, to[i][j].second);
j++;
}
pre[ear] += mn;
while (j < tos[i] && to[i][j].first < lat) {
pre[to[i][j].first + 1] -= mn;
mn = mini(mn, to[i][j].second);
pre[to[i][j].first + 1] += mn;
j++;
}
mn = 100000000;
j = bas[i] - 1;
while (~j && bak[i][j].first - k >= lat) {
mn = mini(mn, bak[i][j].second);
j--;
}
suf[lat] += mn;
while (~j && bak[i][j].first - k >= ear) {
suf[bak[i][j].first - k] -= mn;
mn = mini(mn, bak[i][j].second);
suf[bak[i][j].first - k] += mn;
j--;
}
}
long long res = 1ll << 60, ans = 0;
for (int i = ear; i <= lat; i++) {
ans += suf[i];
}
for (int i = ear; i <= lat; i++) {
ans += pre[i];
res = min(res, ans);
ans -= suf[i];
}
printf("%I64d", res);
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int N = 1E6, M = 1E5;
int n, q, k;
pair<int, long long> dpto0[N + 7], dpleave0[N + 7];
struct node {
int day, u, v, cost;
bool operator<(const node &x) const { return day < x.day; }
} a[M + 7];
struct P {
int to, cost;
};
vector<P> visto0[N + 7], visleave0[N + 7];
void check_min(int &x, int y) {
if (x > y) x = y;
}
void check_max(int &x, int y) {
if (x < y) x = y;
}
int main() {
std::ios::sync_with_stdio(false), cin.tie(0);
cin >> n >> q >> k;
int upto0 = -1, upleave0 = (int)2E9;
for (int i = 1; i <= q; i++) {
cin >> a[i].day >> a[i].u >> a[i].v >> a[i].cost;
if (!a[i].u) {
visleave0[a[i].day].push_back({a[i].v, a[i].cost});
check_min(upleave0, a[i].day);
} else {
visto0[a[i].day].push_back({a[i].u, a[i].cost});
check_max(upto0, a[i].day);
}
}
memset(dpto0, -1, sizeof(dpto0));
memset(dpleave0, -1, sizeof(dpleave0));
vector<bool> vis1(N + 7);
vector<int> cost1(M + 7);
long long cnt = 0, num = 0;
for (int i = 1; i <= upto0; i++) {
for (int j = 0; j < (int)visto0[i].size(); j++) {
if (!vis1[visto0[i][j].to]) {
vis1[visto0[i][j].to] = 1, num++;
cnt += visto0[i][j].cost;
cost1[visto0[i][j].to] = visto0[i][j].cost;
} else {
cnt -= cost1[visto0[i][j].to];
check_min(cost1[visto0[i][j].to], visto0[i][j].cost);
cnt += cost1[visto0[i][j].to];
}
dpto0[i].second = cnt;
dpto0[i].first = num;
}
}
int dayto0 = -1;
for (int i = 1; i <= upto0; i++) {
if (dpto0[i].first == n) {
dayto0 = i;
break;
}
}
if (dayto0 == -1) {
cout << -1 << endl;
return 0;
}
cnt = num = 0;
vector<bool> vis2(N + 7);
vector<int> cost2(M + 7);
for (int i = N; i >= upleave0; i--) {
for (int j = 0; j < (int)visleave0[i].size(); j++) {
if (!vis2[visleave0[i][j].to]) {
vis2[visleave0[i][j].to] = 1, num++;
cnt += visleave0[i][j].cost;
cost2[visleave0[i][j].to] = visleave0[i][j].cost;
} else {
cnt -= cost2[visleave0[i][j].to];
check_min(cost2[visleave0[i][j].to], visleave0[i][j].cost);
cnt += cost2[visleave0[i][j].to];
}
dpleave0[i].second = cnt;
dpleave0[i].first = num;
}
}
int dayleave = -1;
vector<int> leave;
for (int i = upleave0; i <= N; i++) {
if (dpleave0[i].first == n) {
leave.push_back(i);
}
}
if (leave.empty()) {
cout << -1 << endl;
return 0;
}
dayleave = leave[0];
long long ans = 5E18;
bool ok = false;
for (int i = dayto0; i <= upto0; i++) {
if (dpto0[i].second >= n) {
auto it = upper_bound(begin(leave), end(leave), k + i);
if (it != leave.end()) {
ok = true;
ans = min(ans, dpto0[i].second + dpleave0[*it].second);
}
}
}
if (!ok)
cout << -1 << endl;
else
cout << ans << endl;
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 3e6 + 100;
const int mod = 1e9 + 7;
int n, m, k;
long long dp1[MAXN], dp2[MAXN];
struct fc {
int d, u, v;
long long cost;
};
vector<fc> v1;
vector<fc> v2;
bool vis[MAXN];
long long pre[MAXN];
bool cmp(fc a, fc b) { return a.d < b.d; }
bool cmp2(fc a, fc b) { return a.d > b.d; }
int main() {
scanf("%d%d%d", &n, &m, &k);
int maxd = -1;
for (int i = 1; i <= m; i++) {
int d, u, v;
long long cost;
scanf("%d%d%d%lld", &d, &u, &v, &cost);
maxd = max(d, maxd);
if (v == 0)
v1.push_back({d, u, v, cost});
else
v2.push_back({d, u, v, cost});
}
sort(v1.begin(), v1.end(), cmp);
int cnt = 0;
memset(vis, 0, sizeof(vis));
memset(pre, -1, sizeof(pre));
memset(dp1, -1, sizeof(dp1));
long long sum = 0;
for (auto elem : v1) {
int d = elem.d, u = elem.u, v = elem.v;
long long cost = elem.cost;
if (!vis[u]) {
vis[u] = 1;
cnt++;
pre[u] = cost;
sum += cost;
} else {
if (cost < pre[u]) {
sum = sum - pre[u] + cost;
pre[u] = cost;
}
}
if (cnt == n) {
dp1[d] = dp1[d - 1];
if (dp1[d] == -1)
dp1[d] = sum;
else
dp1[d] = min(dp1[d], sum);
}
}
sort(v2.begin(), v2.end(), cmp2);
memset(vis, 0, sizeof(vis));
memset(pre, -1, sizeof(pre));
memset(dp2, -1, sizeof(dp2));
sum = 0;
cnt = 0;
for (auto elem : v2) {
int d = elem.d, v = elem.u, u = elem.v;
long long cost = elem.cost;
if (!vis[u]) {
vis[u] = 1;
cnt++;
pre[u] = cost;
sum += cost;
} else {
if (cost < pre[u]) {
sum = sum - pre[u] + cost;
pre[u] = cost;
}
}
if (cnt == n) {
dp2[d] = dp2[d + 1];
if (dp2[d] == -1)
dp2[d] = sum;
else
dp2[d] = min(dp2[d], sum);
}
}
for (int i = 1; i <= maxd; i++)
if (dp1[i] == -1) dp1[i] = dp1[i - 1];
for (int i = maxd; i >= 1; i--)
if (dp2[i] == -1) dp2[i] = dp2[i + 1];
long long ans = ((long long)0x3f3f3f3f3f3f3f3f);
for (int i = 1; i <= maxd; i++) {
if (dp1[i] != -1 && dp2[i + k + 1] != -1) {
ans = min(dp1[i] + dp2[i + 1 + k], ans);
}
}
if (ans == ((long long)0x3f3f3f3f3f3f3f3f))
cout << "-1" << endl;
else
cout << ans << endl;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
vector<pair<long long, long long> > ar[1000009], dep[1000009];
long long pre[1000009], suf[1000009], pr[100009], prsz[1000009], sufsz[1000009];
int main() {
long long n, m, k, d, f, t, s;
cin >> n >> m >> k;
for (int i = 0; i < m; i++) {
cin >> d >> f >> t >> s;
if (f != 0) {
ar[d].push_back(make_pair(f, s));
} else {
dep[d].push_back(make_pair(t, s));
}
}
for (int i = 1; i < 1000001; i++) {
prsz[i] = prsz[i - 1];
pre[i] = pre[i - 1];
for (int j = 0; j < ar[i].size(); j++) {
long long el = ar[i][j].first, price = ar[i][j].second;
if (pr[el] == 0) {
prsz[i]++;
pr[el] = price;
pre[i] += price;
}
if (pr[el] > price) {
pre[i] -= pr[el];
pr[el] = price;
pre[i] += price;
}
}
}
memset(pr, 0, sizeof(pr));
for (int i = 1000001 - 1; i > 0; i--) {
sufsz[i] = sufsz[i + 1];
suf[i] = suf[i + 1];
for (int j = 0; j < dep[i].size(); j++) {
long long el = dep[i][j].first, price = dep[i][j].second;
if (pr[el] == 0) {
sufsz[i]++;
pr[el] = price;
suf[i] += price;
}
if (pr[el] > price) {
suf[i] -= pr[el];
pr[el] = price;
suf[i] += price;
}
}
}
long long ans = 1e17;
for (int i = 1; i + k + 1 < 1000001; i++) {
if ((prsz[i] == n) && (sufsz[i + k + 1] == n)) {
ans = min(ans, (pre[i] + suf[i + k + 1]));
}
}
if (ans == 1e17)
cout << "-1" << endl;
else
cout << ans << endl;
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
vector<pair<int, int> > f[100005], t[100005];
vector<int> fmx[100005], tmx[100005];
int ptf[100005] = {}, ptt[100005] = {};
vector<int> goingt;
int main() {
int n, m, k;
scanf("%d%d%d", &n, &m, &k);
while (m--) {
int d, fx, tx, c;
scanf("%d%d%d%d", &d, &fx, &tx, &c);
if (tx == 0) {
f[fx].push_back({d, c});
goingt.push_back(d + 1);
} else {
t[tx].push_back({d, c});
}
}
sort(goingt.begin(), goingt.end());
goingt.resize(distance(goingt.begin(), unique(goingt.begin(), goingt.end())));
for (int i = 1; i <= n; i++) {
if (f[i].empty() || t[i].empty()) {
cout << -1 << endl;
return 0;
}
sort(f[i].begin(), f[i].end());
fmx[i].resize(f[i].size());
fmx[i][0] = f[i][0].second;
for (int j = 1; j < f[i].size(); j++) {
fmx[i][j] = min(f[i][j].second, fmx[i][j - 1]);
}
sort(t[i].begin(), t[i].end());
tmx[i].resize(t[i].size());
tmx[i].back() = t[i].back().second;
for (int j = t[i].size() - 2; j >= 0; j--) {
tmx[i][j] = min(t[i][j].second, tmx[i][j + 1]);
}
}
long long ans = 1e15;
for (int i = 0; i < goingt.size(); i++) {
int l = goingt[i];
int r = goingt[i] + k - 1;
bool flag = 1;
long long ctrip = 0;
for (int j = 1; j <= n; j++) {
while (ptf[j] < f[j].size() && f[j][ptf[j]].first < l) {
ptf[j]++;
}
if (ptf[j] == 0) {
flag = 0;
break;
}
ptf[j]--;
if (f[j][ptf[j]].first < l) {
ctrip += fmx[j][ptf[j]];
} else {
flag = 0;
break;
}
while (ptt[j] < t[j].size() && t[j][ptt[j]].first <= r) {
ptt[j]++;
}
if (ptt[j] == t[j].size()) {
ptt[j]--;
flag = 0;
break;
}
if (t[j][ptt[j]].first > r) {
ctrip += tmx[j][ptt[j]];
} else {
flag = 0;
break;
}
}
if (flag) {
ans = min(ans, ctrip);
}
}
if (ans == 1e15) {
cout << -1 << endl;
return 0;
}
cout << ans << endl;
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
long long int inf = 1e17;
long long int n, m, k, i, st, l = 0, ind, e = 0, d, c, j, f, r, bg = 0, lv = 0,
mini[100005], ans = inf;
vector<pair<long long int, pair<long long int, long long int> > > qu[1000005];
multiset<long long int> lea[100005];
multiset<long long int>::iterator it;
int main() {
int tm, tt;
cin >> n >> m >> k;
for (i = 0; i <= n; i++) mini[i] = -1;
for (i = 0; i < m; i++) {
scanf("%I64d%I64d%I64d%I64d", &d, &st, &ind, &c);
ind = max(ind, st);
st = (st == 0);
qu[d].push_back(make_pair(st, make_pair(ind, c)));
if (st == 1) {
if (lea[ind].size() == 0) {
lv += c;
e++;
} else
lv += min(c, *lea[ind].begin()) - *lea[ind].begin();
lea[ind].insert(c);
}
}
j = 0;
f = 0;
if (e < n) {
cout << -1 << endl;
return 0;
}
for (i = 0; i < 1000005 && !f; i++) {
if (qu[i].size() == 0) continue;
for (r = 0; r < qu[i].size(); r++) {
ind = qu[i][r].second.first;
c = qu[i][r].second.second;
if (qu[i][r].first == 0) {
if (mini[ind] == -1) {
mini[ind] = c;
l++;
bg += c;
} else {
tm = mini[ind];
mini[ind] = min(mini[ind], c);
bg += mini[ind] - tm;
}
}
}
while (j < 1000001 && j <= i + k) {
if (qu[j].size() == 0) {
j++;
continue;
}
for (r = 0; r < qu[j].size(); r++) {
ind = qu[j][r].second.first;
c = qu[j][r].second.second;
if (qu[j][r].first == 1) {
tm = *lea[ind].begin();
it = lea[ind].find(c);
lea[ind].erase(it);
if (lea[ind].size() == 0) {
f = 1;
break;
}
tt = *lea[ind].begin();
lv += (tt - tm);
}
}
j++;
}
if (j <= i + k) break;
if (l == n && !f) ans = min(ans, lv + bg);
}
if (ans == inf)
cout << -1 << endl;
else
cout << ans << endl;
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | from bisect import *
from sys import *
n,m,k=[int(i) for i in input().split()]
pln=[]
if m==0:
print(-1)
exit(0)
for i in range(m):
pln.append([int(i) for i in input().split()])
pln.sort()
grp=[[pln[0]]];gt=0;
for i in range(1,m):
if pln[i][0]!=pln[i-1][0]:
gt=gt+1
grp.append([])
grp[gt].append(pln[i])
xx=[]
for i in range(len(grp)):
xx.append(grp[i][0][0])
#print('grp',grp)
#print('xx',xx)
from math import inf
pre=[0]*len(xx)
ct=0
mincost=[inf]*(n+1);sumcost=inf
for i,x in enumerate(grp):
for di,fi,ti,ci in x:
if ti==0:
if mincost[fi]==inf:
ct+=1
if sumcost==inf:
mincost[fi]=min(mincost[fi],ci)
else:
sumcost=sumcost-mincost[fi]
mincost[fi]=min(mincost[fi],ci)
sumcost=sumcost+mincost[fi]
if ct==n and sumcost==inf:
sumcost=sum(mincost[1:])
pre[i]=sumcost
#print(pre)
sa=[0]*len(xx)
ct=0
mincost=[inf]*(n+1);sumcost=inf
grp.reverse()
for i,x in enumerate(grp):
for di,fi,ti,ci in x:
if fi==0:
if mincost[ti]==inf:
ct+=1
if sumcost==inf:
mincost[ti]=min(mincost[ti],ci)
else:
sumcost=sumcost-mincost[ti]
mincost[ti]=min(mincost[ti],ci)
sumcost=sumcost+mincost[ti]
if ct==n and sumcost==inf:
sumcost=sum(mincost[1:])
sa[i]=sumcost
sa.reverse()
#print(sa)
ans=inf
for l,xxi in enumerate(xx):
r=bisect_right(xx,xxi+k)
ansl=pre[l]
ansr= inf if r==len(xx) else sa[r]
ans=min(ans,ansl+ansr)
print(ans) if ans!=inf else print(-1)
| PYTHON3 |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1000005;
const int limit = 1000000;
struct Info {
int id;
int cost;
Info() {}
Info(int i, int c) : id(i), cost(c) {}
};
Info info;
int n, m, k;
int arrived[maxn], totol_arrived[2][maxn];
long long totol_arrived_cost[2][maxn];
vector<Info> arrived_store[2][maxn];
void compute(int type, int day) {
for (int i = 0; i < arrived_store[type][day].size(); ++i) {
info = arrived_store[type][day][i];
if (arrived[info.id] == 0) {
arrived[info.id] = info.cost;
totol_arrived[type][day] += 1;
totol_arrived_cost[type][day] += info.cost;
} else {
if (arrived[info.id] > info.cost) {
totol_arrived_cost[type][day] -= arrived[info.id];
totol_arrived_cost[type][day] += info.cost;
arrived[info.id] = info.cost;
;
}
}
}
}
void init() {
for (int i = 1; i <= limit; ++i) {
totol_arrived[0][i] = totol_arrived[0][i - 1];
totol_arrived_cost[0][i] = totol_arrived_cost[0][i - 1];
compute(0, i);
}
memset(arrived, 0, sizeof(arrived));
for (int i = limit; i >= 1; --i) {
totol_arrived[1][i] = totol_arrived[1][i + 1];
totol_arrived_cost[1][i] = totol_arrived_cost[1][i + 1];
compute(1, i);
}
}
long long solve() {
long long ret = 0x7fffffffffffffffLL;
for (int u = 1; u <= limit; ++u) {
int v = u + 1 + k;
if (u > limit) {
continue;
}
if (totol_arrived[0][u] == n && totol_arrived[1][v] == n) {
ret = min(ret, totol_arrived_cost[0][u] + totol_arrived_cost[1][v]);
}
}
if (ret == 0x7fffffffffffffffLL) {
return -1ll;
} else {
return ret;
}
}
int main() {
int t, u, v, c;
cin >> n >> m >> k;
for (int i = 0; i < m; ++i) {
cin >> t >> u >> v >> c;
if (u == 0) {
arrived_store[1][t].push_back(Info(v, c));
} else {
arrived_store[0][t].push_back(Info(u, c));
}
}
init();
long long ans = solve();
cout << ans << endl;
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
struct flight {
int u, v, c;
flight(int U, int V, int C) : u(U), v(V), c(C) {}
};
int n, m, k;
long long pre[1111000], suf[1111000], best[1111000], INF = 15e11, tot;
vector<flight> vet[1111000];
int main() {
scanf("%d%d%d", &n, &m, &k);
for (int(i) = (0); (i) < (m); (i)++) {
int d, u, v, c;
scanf("%d%d%d%d", &d, &u, &v, &c);
vet[d].push_back(flight(u, v, c));
}
tot = INF * n;
pre[0] = tot;
for (int(i) = (1); (i) < (n + 1); (i)++) best[i] = INF;
for (int(i) = (1); (i) < (1111000); (i)++) {
for (int(j) = (0); (j) < (((int)(vet[i]).size())); (j)++)
if (vet[i][j].u) {
int u = vet[i][j].u, c = vet[i][j].c;
tot -= best[u];
best[u] = min(best[u], (long long)c);
tot += best[u];
}
pre[i] = tot;
}
tot = INF * n;
suf[1111000 - 1] = tot;
for (int(i) = (1); (i) < (n + 1); (i)++) best[i] = INF;
for (int(i) = (1111000 - 2); (i) >= (0); (i)--) {
for (int(j) = (0); (j) < (((int)(vet[i]).size())); (j)++)
if (vet[i][j].v) {
int v = vet[i][j].v, c = vet[i][j].c;
tot -= best[v];
best[v] = min(best[v], (long long)c);
tot += best[v];
}
suf[i] = tot;
}
long long ans = INF;
for (int(i) = (0); (i) < (1111000 - 10 - k); (i)++)
ans = min(ans, pre[i] + suf[k + i + 1]);
if (ans == INF)
puts("-1");
else
printf("%lld\n", ans);
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
struct node1 {
int f, ti;
long long c;
} a[N];
struct node2 {
int to, ti;
long long c;
} b[N];
bool cmp1(node1 a, node1 b) { return a.ti < b.ti; };
bool cmp2(node2 a, node2 b) { return a.ti > b.ti; };
bool vis[N];
long long pre[N];
long long dp1[N], dp2[N];
int main() {
int n, m, k, d, f, t;
long long c;
scanf("%d%d%d", &n, &m, &k);
int cnt1 = 0, cnt2 = 0;
for (int i = 1; i <= m; i++) {
scanf("%d%d%d%I64d", &d, &f, &t, &c);
if (f == 0) {
cnt2++;
b[cnt2].to = t, b[cnt2].c = c, b[cnt2].ti = d;
} else {
cnt1++;
a[cnt1].f = f, a[cnt1].c = c, a[cnt1].ti = d;
}
}
int num = 0;
long long sum = 0;
sort(a + 1, a + cnt1 + 1, cmp1);
for (int i = 1; i <= cnt1; i++) {
if (!vis[a[i].f]) {
vis[a[i].f] = 1;
num++;
pre[a[i].f] = a[i].c;
sum += a[i].c;
} else {
if (pre[a[i].f] > a[i].c) {
sum += (a[i].c - pre[a[i].f]);
pre[a[i].f] = a[i].c;
}
}
if (num == n) dp1[a[i].ti] = sum;
}
sort(b + 1, b + cnt2 + 1, cmp2);
memset(vis, 0, sizeof(vis));
num = 0;
sum = 0;
for (int i = 1; i <= cnt2; i++) {
if (!vis[b[i].to]) {
vis[b[i].to] = 1;
num++;
pre[b[i].to] = b[i].c;
sum += b[i].c;
} else {
if (pre[b[i].to] > b[i].c) {
sum += (b[i].c - pre[b[i].to]);
pre[b[i].to] = b[i].c;
}
}
if (num == n) dp2[b[i].ti] = sum;
}
for (int i = 1; i + 1 < N; i++)
if (!dp1[i + 1]) dp1[i + 1] = dp1[i];
for (int i = N - 1; i > 0; i--)
if (!dp2[i - 1]) dp2[i - 1] = dp2[i];
long long ans = 1e18;
for (int i = 1; i + k + 1 < N; i++) {
if (dp1[i] == 0 || dp2[i + k + 1] == 0) continue;
ans = min(ans, dp1[i] + dp2[i + k + 1]);
}
if (ans >= 1e18)
printf("-1\n");
else
printf("%I64d\n", ans);
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int maxx = 1000010;
priority_queue<long long, vector<long long>, greater<long long> >
q[maxx / 10 + 10000];
long long t, n, m, k;
long long ans = 0, total = 0, sum = 0, cnt = 0, l = 0, l1 = 0, r1 = 0;
long long a[maxx], sum1[maxx], sum2[maxx], bj1[maxx], bj2[maxx];
struct node {
long long d;
long long f;
long long t;
long long c;
} s[maxx];
bool cmp(node a, node b) { return a.f > b.f; }
bool cm(node a, node b) {
if (a.d == b.d) {
if (a.f == b.f) return a.c < b.c;
return a.f < b.f;
}
return a.d < b.d;
}
int main() {
scanf("%lld%lld%lld", &n, &m, &k);
if (m == 0) {
printf("-1");
return 0;
}
for (register int i = 1; i <= m; i++)
scanf("%lld%lld%lld%lld", &s[i].d, &s[i].f, &s[i].t, &s[i].c);
sort(s + 1, s + m + 1, cmp);
for (register int i = 1; i <= m; i++)
if (s[i].f == 0) {
l = i;
break;
}
sort(s + 1, s + l, cm);
sort(s + l, s + m + 1, cm);
for (register int i = 1; i <= l - 1; i++) {
bj1[i] = bj1[i - 1];
sum1[i] = sum1[i - 1];
if (!q[s[i].f].size()) {
bj1[i]++;
q[s[i].f].push(s[i].c);
sum1[i] += s[i].c;
} else {
sum1[i] -= q[s[i].f].top();
q[s[i].f].push(s[i].c);
sum1[i] += q[s[i].f].top();
}
}
for (register int i = 1; i <= n; i++)
while (!q[i].empty()) {
q[i].pop();
}
for (register int i = m; i >= l; i--) {
bj2[i] = bj2[i + 1];
sum2[i] = sum2[i + 1];
if (!q[s[i].t].size()) {
bj2[i]++;
q[s[i].t].push(s[i].c);
sum2[i] += s[i].c;
} else {
sum2[i] -= q[s[i].t].top();
q[s[i].t].push(s[i].c);
sum2[i] += q[s[i].t].top();
}
}
l1 = l - 1, r1 = l;
if (bj1[l1] != n || bj2[r1] != n) {
printf("-1");
return 0;
}
ans = 1e16;
sum = 0;
while (l1 >= 1) {
long long l2 = l, r2 = m, kl = 0;
while (l2 <= r2) {
long long mid = (l2 + r2) >> 1;
if (bj2[mid] != n)
r2 = mid - 1;
else {
if (s[mid].d - s[l1].d - 1 >= k) {
kl = mid;
r2 = mid - 1;
} else
l2 = mid + 1;
}
}
if (kl) ans = min(ans, sum1[l1] + sum2[kl]);
l1--, r1 = l;
if (bj1[l1] != n) break;
}
if (ans == 1e16)
printf("-1");
else
printf("%lld", ans);
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
vector<pair<long long, long long>> in[1000010], out[1000010];
long long inc[1000010], outc[1000010], was[100010];
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
long long n, m, k;
cin >> n >> m >> k;
for (long long i = 0; i < m; i++) {
long long d, f, t, c;
cin >> d >> f >> t >> c;
if (t == 0) in[d].push_back({c, f});
if (f == 0) out[d].push_back({c, t});
}
for (long long i = 0; i < 1000005; i++) inc[i] = outc[i] = 1e18;
for (long long i = 0; i < 100005; i++) was[i] = 1e18;
long long visit = 0;
long long cost = 0;
for (long long i = 0; i < 1000005; i++) {
for (auto j : in[i]) {
if (was[j.second] == 1e18) {
visit++;
cost += j.first;
was[j.second] = j.first;
} else if (was[j.second] > j.first) {
cost += j.first - was[j.second];
was[j.second] = j.first;
}
}
if (visit == n) inc[i] = cost;
}
for (long long i = 0; i < 100005; i++) was[i] = 1e18;
visit = 0, cost = 0;
for (long long i = 1000005; i >= 0; i--) {
for (auto j : out[i]) {
if (was[j.second] == 1e18) {
visit++;
cost += j.first;
was[j.second] = j.first;
} else if (was[j.second] > j.first) {
cost += j.first - was[j.second];
was[j.second] = j.first;
}
}
if (visit == n) outc[i] = cost;
}
long long ans = 1e18;
for (long long i = 0; i + k < 1000001; i++) {
ans = min(ans, inc[i] + outc[i + k + 1]);
}
if (ans == 1e18)
cout << "-1\n";
else
cout << ans << "\n";
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int maxN = (int)1e5 + 100;
const int INF = 1e9;
const int maxD = 1e6 + 100;
const int modulo = maxN;
int d[maxN], f[maxN], t[maxN], c[maxN];
int start[maxN], finish[maxN];
long long cost0[maxD], costN[maxD];
vector<pair<int, int> > FROM[maxD], TO[maxD];
long long rsq[maxN * 4];
void replace(int i, long long x) {
i += modulo - 1;
rsq[i] = min(rsq[i], x);
i /= 2;
while (i > 0) {
rsq[i] = rsq[i + i] + rsq[i + i + 1];
i /= 2;
}
}
long long getsum(int l, int r) {
int i = l + modulo - 1, j = r + modulo - 1;
long long ans = 0;
while (i <= j) {
if (i % 2 == 1) ans += rsq[i];
if (j % 2 == 0) ans += rsq[j];
i = (i + 1) / 2;
j = (j - 1) / 2;
}
return ans;
}
void solveTask() {
int n, m, k;
scanf("%d%d%d", &n, &m, &k);
for (int i = 1; i <= m; ++i) {
scanf("%d%d%d%d", &d[i], &f[i], &t[i], &c[i]);
}
for (int i = 1; i <= n; ++i) {
start[i] = INF;
finish[i] = -INF;
}
for (int i = 1; i <= m; ++i) {
if (t[i] == 0) start[f[i]] = min(start[f[i]], d[i] + 1);
if (f[i] == 0) finish[t[i]] = max(finish[t[i]], d[i] - 1);
if (t[i] == 0) {
FROM[d[i]].push_back(make_pair(f[i], c[i]));
}
if (f[i] == 0) {
TO[d[i]].push_back(make_pair(t[i], c[i]));
}
}
for (int i = 1; i <= n; ++i) {
if (start[i] == INF || finish[i] == -INF) {
cout << -1 << endl;
return;
}
}
int minK = -INF, maxK = INF;
for (int i = 1; i <= n; ++i) {
minK = max(minK, start[i]);
maxK = min(maxK, finish[i]);
}
if (maxK - minK + 1 < k) {
cout << -1 << endl;
return;
}
for (int i = 0; i <= 1e6; ++i) {
cost0[i] = 1e18, costN[i] = 1e18;
}
int possibleL = minK, possibleR = maxK - k + 1;
for (int i = 0; i < maxN * 4; ++i) {
rsq[i] = 1e13;
}
for (int t = 1; t < possibleL; ++t) {
for (int i = 0; i < FROM[t].size(); ++i) {
pair<int, int> cur_pair = FROM[t][i];
replace(cur_pair.first, cur_pair.second);
}
}
for (int i = possibleL; i <= possibleR; ++i) {
cost0[i] = getsum(1, n);
for (int j = 0; j < FROM[i].size(); ++j) {
pair<int, int> cur_pair = FROM[i][j];
replace(cur_pair.first, cur_pair.second);
}
}
for (int i = 0; i < maxN * 4; ++i) {
rsq[i] = 1e13;
}
for (int t = 1e6; t >= possibleR + k; --t) {
for (int i = 0; i < TO[t].size(); ++i) {
pair<int, int> cur_pair = TO[t][i];
replace(cur_pair.first, cur_pair.second);
}
}
for (int t = possibleR + k - 1; t >= k; --t) {
costN[t - k + 1] = getsum(1, n);
for (int j = 0; j < TO[t].size(); ++j) {
pair<int, int> cur_pair = TO[t][j];
replace(cur_pair.first, cur_pair.second);
}
}
long long answer = 1e18;
for (int i = 0; i <= 1e6; ++i) {
answer = min(answer, cost0[i] + costN[i]);
}
if (answer < 1e18) {
cout << answer << endl;
} else {
cout << -1 << endl;
}
}
int main() {
solveTask();
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;
public class D_433
{
public static final long[] POWER2 = generatePOWER2();
public static final IteratorBuffer<Long> ITERATOR_BUFFER_PRIME = new IteratorBuffer<>(streamPrime(1000000).iterator());
private static BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
private static StringTokenizer stringTokenizer = null;
private static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
interface BiFunctionResult<Type0, Type1, TypeResult>
{
TypeResult apply(Type0 x0, Type1 x1, TypeResult x2);
}
static class Array<Type> implements Iterable<Type>
{
private final Object[] array;
public Array(int size)
{
this.array = new Object[size];
}
public Array(int size, Type element)
{
this(size);
Arrays.fill(this.array, element);
}
public Array(Array<Type> array, Type element)
{
this(array.size() + 1);
for (int index = 0; index < array.size(); index++)
{
set(index, array.get(index));
}
set(size() - 1, element);
}
public Array(List<Type> list)
{
this(list.size());
int index = 0;
for (Type element : list)
{
set(index, element);
index += 1;
}
}
public Type get(int index)
{
return (Type) this.array[index];
}
public Array set(int index, Type value)
{
this.array[index] = value;
return this;
}
public int size()
{
return this.array.length;
}
public List<Type> toList()
{
List<Type> result = new ArrayList<>();
for (Type element : this)
{
result.add(element);
}
return result;
}
@Override
public Iterator<Type> iterator()
{
return new Iterator<Type>()
{
int index = 0;
@Override
public boolean hasNext()
{
return this.index < size();
}
@Override
public Type next()
{
Type result = Array.this.get(index);
index += 1;
return result;
}
};
}
@Override
public String toString()
{
return "[" + D_433.toString(this, ", ") + "]";
}
}
static class BIT
{
private static int lastBit(int index)
{
return index & -index;
}
private final long[] tree;
public BIT(int size)
{
this.tree = new long[size];
}
public void add(int index, long delta)
{
index += 1;
while (index <= this.tree.length)
{
tree[index - 1] += delta;
index += lastBit(index);
}
}
private long prefix(int end)
{
long result = 0;
while (end > 0)
{
result += this.tree[end - 1];
end -= lastBit(end);
}
return result;
}
public int size()
{
return this.tree.length;
}
public long sum(int start, int end)
{
return prefix(end) - prefix(start);
}
}
static abstract class Edge<TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>>
{
public final TypeVertex vertex0;
public final TypeVertex vertex1;
public final boolean bidirectional;
public Edge(TypeVertex vertex0, TypeVertex vertex1, boolean bidirectional)
{
this.vertex0 = vertex0;
this.vertex1 = vertex1;
this.bidirectional = bidirectional;
this.vertex0.edges.add(getThis());
if (this.bidirectional)
{
this.vertex1.edges.add(getThis());
}
}
public TypeVertex other(Vertex<TypeVertex, TypeEdge> vertex)
{
TypeVertex result;
if (vertex0 == vertex)
{
result = vertex1;
}
else
{
result = vertex0;
}
return result;
}
public abstract TypeEdge getThis();
public void remove()
{
this.vertex0.edges.remove(getThis());
if (this.bidirectional)
{
this.vertex1.edges.remove(getThis());
}
}
@Override
public String toString()
{
return this.vertex0 + "->" + this.vertex1;
}
}
public static class EdgeDefault<TypeVertex extends Vertex<TypeVertex, EdgeDefault<TypeVertex>>> extends Edge<TypeVertex, EdgeDefault<TypeVertex>>
{
public EdgeDefault(TypeVertex vertex0, TypeVertex vertex1, boolean bidirectional)
{
super(vertex0, vertex1, bidirectional);
}
@Override
public EdgeDefault<TypeVertex> getThis()
{
return this;
}
}
public static class Vertex<TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>> implements Comparable<Vertex<? super TypeVertex, ? super TypeEdge>>
{
public static <TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>> void depthFirstSearch(
Array<TypeVertex> vertices,
int indexVertexStart,
BiConsumer<TypeVertex, TypeEdge> functionPreVisit,
BiConsumer<TypeVertex, TypeEdge> functionInVisit,
BiConsumer<TypeVertex, TypeEdge> functionPostVisit
)
{
TypeVertex vertexTo;
TypeEdge edgeTo;
boolean[] isOnStack = new boolean[vertices.size()];
Stack<Operation> stackOperations = new Stack<>();
Stack<TypeVertex> stackVertices = new Stack<>();
Stack<TypeEdge> stackEdges = new Stack<>();
TypeVertex vertexStart = vertices.get(indexVertexStart);
stackOperations.push(Operation.EXPAND);
stackVertices.push(vertexStart);
stackEdges.push(null);
isOnStack[vertexStart.index] = true;
while (!stackOperations.isEmpty())
{
Operation operation = stackOperations.pop();
TypeVertex vertex = stackVertices.pop();
TypeEdge edge = stackEdges.pop();
switch (operation)
{
case INVISIT:
functionInVisit.accept(vertex, edge);
break;
case POSTVISIT:
functionPostVisit.accept(vertex, edge);
break;
case EXPAND:
stackOperations.push(Operation.POSTVISIT);
stackVertices.push(vertex);
stackEdges.push(edge);
Integer indexTo = null;
for (int index = 0; indexTo == null && index < vertex.edges.size(); index++)
{
edgeTo = vertex.edges.get(index);
vertexTo = edgeTo.other(vertex);
if (!isOnStack[vertexTo.index])
{
indexTo = index;
}
}
if (indexTo != null)
{
edgeTo = vertex.edges.get(indexTo);
vertexTo = edgeTo.other(vertex);
stackOperations.push(Operation.EXPAND);
stackVertices.push(vertexTo);
stackEdges.push(edgeTo);
isOnStack[vertexTo.index] = true;
for (int index = indexTo + 1; index < vertex.edges.size(); index++)
{
edgeTo = vertex.edges.get(index);
vertexTo = edgeTo.other(vertex);
if (!isOnStack[vertexTo.index])
{
stackOperations.push(Operation.INVISIT);
stackVertices.push(vertex);
stackEdges.push(edge);
stackOperations.push(Operation.EXPAND);
stackVertices.push(vertexTo);
stackEdges.push(edgeTo);
isOnStack[vertexTo.index] = true;
}
}
}
functionPreVisit.accept(vertex, edge);
break;
}
}
}
public static <TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>> void depthFirstSearch(
Array<TypeVertex> vertices,
int indexVertexStart,
Consumer<TypeVertex> functionPreVisit,
Consumer<TypeVertex> functionInVisit,
Consumer<TypeVertex> functionPostVisit
)
{
depthFirstSearch(
vertices,
indexVertexStart,
(vertex, edge) -> functionPreVisit.accept(vertex),
(vertex, edge) -> functionInVisit.accept(vertex),
(vertex, edge) -> functionPostVisit.accept(vertex)
);
}
public static <TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>, TypeResult> TypeResult breadthFirstSearch(
TypeVertex vertex,
TypeEdge edge,
BiFunctionResult<TypeVertex, TypeEdge, TypeResult> function,
Array<Boolean> visited,
FIFO<TypeVertex> verticesNext,
FIFO<TypeEdge> edgesNext,
TypeResult result
)
{
if (!visited.get(vertex.index))
{
visited.set(vertex.index, true);
result = function.apply(vertex, edge, result);
for (TypeEdge edgeNext : vertex.edges)
{
TypeVertex vertexNext = edgeNext.other(vertex);
if (!visited.get(vertexNext.index))
{
verticesNext.push(vertexNext);
edgesNext.push(edgeNext);
}
}
}
return result;
}
public static <TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>, TypeResult> TypeResult breadthFirstSearch(
Array<TypeVertex> vertices,
int indexVertexStart,
BiFunctionResult<TypeVertex, TypeEdge, TypeResult> function,
TypeResult result
)
{
Array<Boolean> visited = new Array<>(vertices.size(), false);
FIFO<TypeVertex> verticesNext = new FIFO<>();
verticesNext.push(vertices.get(indexVertexStart));
FIFO<TypeEdge> edgesNext = new FIFO<>();
edgesNext.push(null);
while (!verticesNext.isEmpty())
{
result = breadthFirstSearch(verticesNext.pop(), edgesNext.pop(), function, visited, verticesNext, edgesNext, result);
}
return result;
}
public final int index;
public final List<TypeEdge> edges;
public Vertex(int index)
{
this.index = index;
this.edges = new ArrayList<>();
}
@Override
public int compareTo(Vertex<? super TypeVertex, ? super TypeEdge> that)
{
return Integer.compare(this.index, that.index);
}
@Override
public String toString()
{
return "" + this.index;
}
enum Operation
{
INVISIT, POSTVISIT, EXPAND
}
}
public static class VertexDefault<TypeEdge extends Edge<VertexDefault<TypeEdge>, TypeEdge>> extends Vertex<VertexDefault<TypeEdge>, TypeEdge>
{
public VertexDefault(int index)
{
super(index);
}
}
public static class VertexDefaultDefault extends Vertex<VertexDefaultDefault, EdgeDefaultDefault>
{
public static Array<VertexDefaultDefault> vertices(int n)
{
Array<VertexDefaultDefault> result = new Array<>(n);
for (int index = 0; index < n; index++)
{
result.set(index, new VertexDefaultDefault(index));
}
return result;
}
public VertexDefaultDefault(int index)
{
super(index);
}
}
public static class EdgeDefaultDefault extends Edge<VertexDefaultDefault, EdgeDefaultDefault>
{
public EdgeDefaultDefault(VertexDefaultDefault vertex0, VertexDefaultDefault vertex1, boolean bidirectional)
{
super(vertex0, vertex1, bidirectional);
}
@Override
public EdgeDefaultDefault getThis()
{
return this;
}
}
public static class Tuple2<Type0, Type1>
{
public final Type0 v0;
public final Type1 v1;
public Tuple2(Type0 v0, Type1 v1)
{
this.v0 = v0;
this.v1 = v1;
}
@Override
public String toString()
{
return "(" + this.v0 + ", " + this.v1 + ")";
}
}
static class Wrapper<Type>
{
public Type value;
public Wrapper(Type value)
{
this.value = value;
}
public Type get()
{
return this.value;
}
public void set(Type value)
{
this.value = value;
}
@Override
public String toString()
{
return this.value.toString();
}
}
public static class Tuple3<Type0, Type1, Type2>
{
public final Type0 v0;
public final Type1 v1;
public final Type2 v2;
public Tuple3(Type0 v0, Type1 v1, Type2 v2)
{
this.v0 = v0;
this.v1 = v1;
this.v2 = v2;
}
@Override
public String toString()
{
return "(" + this.v0 + ", " + this.v1 + ", " + this.v2 + ")";
}
}
public static class Tuple2Comparable<Type0 extends Comparable<? super Type0>, Type1 extends Comparable<? super Type1>> extends Tuple2<Type0, Type1> implements Comparable<Tuple2Comparable<Type0, Type1>>
{
public Tuple2Comparable(Type0 v0, Type1 v1)
{
super(v0, v1);
}
@Override
public int compareTo(Tuple2Comparable<Type0, Type1> that)
{
int result = this.v0.compareTo(that.v0);
if (result == 0)
{
result = this.v1.compareTo(that.v1);
}
return result;
}
}
public static class SingleLinkedList<Type>
{
public final Type element;
public SingleLinkedList<Type> next;
public SingleLinkedList(Type element, SingleLinkedList<Type> next)
{
this.element = element;
this.next = next;
}
public void toCollection(Collection<Type> collection)
{
if (this.next != null)
{
this.next.toCollection(collection);
}
collection.add(this.element);
}
}
public static class Node<Type>
{
public static <Type> Node<Type> balance(Node<Type> result)
{
while (result != null && 1 < Math.abs(height(result.left) - height(result.right)))
{
if (height(result.left) < height(result.right))
{
Node<Type> right = result.right;
if (height(right.right) < height(right.left))
{
result = new Node<>(result.value, result.left, right.rotateRight());
}
result = result.rotateLeft();
}
else
{
Node<Type> left = result.left;
if (height(left.left) < height(left.right))
{
result = new Node<>(result.value, left.rotateLeft(), result.right);
}
result = result.rotateRight();
}
}
return result;
}
public static <Type> Node<Type> clone(Node<Type> result)
{
if (result != null)
{
result = new Node<>(result.value, clone(result.left), clone(result.right));
}
return result;
}
public static <Type> Node<Type> delete(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = null;
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
if (node.left == null)
{
result = node.right;
}
else
{
if (node.right == null)
{
result = node.left;
}
else
{
Node<Type> first = first(node.right);
result = new Node<>(first.value, node.left, delete(node.right, first.value, comparator));
}
}
}
else
{
if (compare < 0)
{
result = new Node<>(node.value, delete(node.left, value, comparator), node.right);
}
else
{
result = new Node<>(node.value, node.left, delete(node.right, value, comparator));
}
}
result = balance(result);
}
return result;
}
public static <Type> Node<Type> first(Node<Type> result)
{
while (result.left != null)
{
result = result.left;
}
return result;
}
public static <Type> Node<Type> get(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = null;
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
result = node;
}
else
{
if (compare < 0)
{
result = get(node.left, value, comparator);
}
else
{
result = get(node.right, value, comparator);
}
}
}
return result;
}
public static <Type> Node<Type> head(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = null;
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
result = node.left;
}
else
{
if (compare < 0)
{
result = head(node.left, value, comparator);
}
else
{
result = new Node<>(node.value, node.left, head(node.right, value, comparator));
}
}
result = balance(result);
}
return result;
}
public static int height(Node node)
{
return node == null ? 0 : node.height;
}
public static <Type> Node<Type> insert(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = new Node<>(value, null, null);
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
result = new Node<>(value, node.left, node.right);
;
}
else
{
if (compare < 0)
{
result = new Node<>(node.value, insert(node.left, value, comparator), node.right);
}
else
{
result = new Node<>(node.value, node.left, insert(node.right, value, comparator));
}
}
result = balance(result);
}
return result;
}
public static <Type> Node<Type> last(Node<Type> result)
{
while (result.right != null)
{
result = result.right;
}
return result;
}
public static int size(Node node)
{
return node == null ? 0 : node.size;
}
public static <Type> Node<Type> tail(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = null;
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
result = new Node<>(node.value, null, node.right);
}
else
{
if (compare < 0)
{
result = new Node<>(node.value, tail(node.left, value, comparator), node.right);
}
else
{
result = tail(node.right, value, comparator);
}
}
result = balance(result);
}
return result;
}
public static <Type> void traverseOrderIn(Node<Type> node, Consumer<Type> consumer)
{
if (node != null)
{
traverseOrderIn(node.left, consumer);
consumer.accept(node.value);
traverseOrderIn(node.right, consumer);
}
}
public final Type value;
public final Node<Type> left;
public final Node<Type> right;
public final int size;
private final int height;
public Node(Type value, Node<Type> left, Node<Type> right)
{
this.value = value;
this.left = left;
this.right = right;
this.size = 1 + size(left) + size(right);
this.height = 1 + Math.max(height(left), height(right));
}
public Node<Type> rotateLeft()
{
Node<Type> left = new Node<>(this.value, this.left, this.right.left);
return new Node<>(this.right.value, left, this.right.right);
}
public Node<Type> rotateRight()
{
Node<Type> right = new Node<>(this.value, this.left.right, this.right);
return new Node<>(this.left.value, this.left.left, right);
}
}
public static class SortedSetAVL<Type> implements SortedSet<Type>
{
public Comparator<? super Type> comparator;
public Node<Type> root;
private SortedSetAVL(Comparator<? super Type> comparator, Node<Type> root)
{
this.comparator = comparator;
this.root = root;
}
public SortedSetAVL(Comparator<? super Type> comparator)
{
this(comparator, null);
}
public SortedSetAVL(Collection<? extends Type> collection, Comparator<? super Type> comparator)
{
this(comparator, null);
this.addAll(collection);
}
public SortedSetAVL(SortedSetAVL<Type> sortedSetAVL)
{
this(sortedSetAVL.comparator, Node.clone(sortedSetAVL.root));
}
@Override
public void clear()
{
this.root = null;
}
@Override
public Comparator<? super Type> comparator()
{
return this.comparator;
}
public Type get(Type value)
{
Node<Type> node = Node.get(this.root, value, this.comparator);
return node == null ? null : node.value;
}
@Override
public SortedSetAVL<Type> subSet(Type valueStart, Type valueEnd)
{
return tailSet(valueStart).headSet(valueEnd);
}
@Override
public SortedSetAVL<Type> headSet(Type valueEnd)
{
return new SortedSetAVL<>(this.comparator, Node.head(this.root, valueEnd, this.comparator));
}
@Override
public SortedSetAVL<Type> tailSet(Type valueStart)
{
return new SortedSetAVL<>(this.comparator, Node.tail(this.root, valueStart, this.comparator));
}
@Override
public Type first()
{
return Node.first(this.root).value;
}
@Override
public Type last()
{
return Node.last(this.root).value;
}
@Override
public int size()
{
return this.root == null ? 0 : this.root.size;
}
@Override
public boolean isEmpty()
{
return this.root == null;
}
@Override
public boolean contains(Object value)
{
return Node.get(this.root, (Type) value, this.comparator) != null;
}
@Override
public Iterator<Type> iterator()
{
Stack<Node<Type>> path = new Stack<>();
return new Iterator<Type>()
{
{
push(SortedSetAVL.this.root);
}
public void push(Node<Type> node)
{
while (node != null)
{
path.push(node);
node = node.left;
}
}
@Override
public boolean hasNext()
{
return !path.isEmpty();
}
@Override
public Type next()
{
if (path.isEmpty())
{
throw new NoSuchElementException();
}
else
{
Node<Type> node = path.peek();
Type result = node.value;
if (node.right != null)
{
push(node.right);
}
else
{
do
{
node = path.pop();
}
while (!path.isEmpty() && path.peek().right == node);
}
return result;
}
}
};
}
@Override
public Object[] toArray()
{
List<Object> list = new ArrayList<>();
Node.traverseOrderIn(this.root, list::add);
return list.toArray();
}
@Override
public <T> T[] toArray(T[] ts)
{
throw new UnsupportedOperationException();
}
@Override
public boolean add(Type value)
{
int sizeBefore = size();
this.root = Node.insert(this.root, value, this.comparator);
return sizeBefore != size();
}
@Override
public boolean remove(Object value)
{
int sizeBefore = size();
this.root = Node.delete(this.root, (Type) value, this.comparator);
return sizeBefore != size();
}
@Override
public boolean containsAll(Collection<?> collection)
{
return collection.stream()
.allMatch(this::contains);
}
@Override
public boolean addAll(Collection<? extends Type> collection)
{
return collection.stream()
.map(this::add)
.reduce(true, (x, y) -> x | y);
}
@Override
public boolean retainAll(Collection<?> collection)
{
SortedSetAVL<Type> set = new SortedSetAVL<>(this.comparator);
collection.stream()
.map(element -> (Type) element)
.filter(this::contains)
.forEach(set::add);
boolean result = size() != set.size();
this.root = set.root;
return result;
}
@Override
public boolean removeAll(Collection<?> collection)
{
return collection.stream()
.map(this::remove)
.reduce(true, (x, y) -> x | y);
}
@Override
public String toString()
{
return "{" + D_433.toString(this, ", ") + "}";
}
}
public static class SortedMapAVL<TypeKey, TypeValue> implements SortedMap<TypeKey, TypeValue>
{
public final Comparator<? super TypeKey> comparator;
public final SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet;
public SortedMapAVL(Comparator<? super TypeKey> comparator)
{
this(comparator, new SortedSetAVL<>((entry0, entry1) -> comparator.compare(entry0.getKey(), entry1.getKey())));
}
private SortedMapAVL(Comparator<? super TypeKey> comparator, SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet)
{
this.comparator = comparator;
this.entrySet = entrySet;
}
@Override
public Comparator<? super TypeKey> comparator()
{
return this.comparator;
}
@Override
public SortedMapAVL<TypeKey, TypeValue> subMap(TypeKey keyStart, TypeKey keyEnd)
{
return new SortedMapAVL<>(this.comparator, this.entrySet.subSet(new AbstractMap.SimpleEntry<>(keyStart, null), new AbstractMap.SimpleEntry<>(keyEnd, null)));
}
@Override
public SortedMapAVL<TypeKey, TypeValue> headMap(TypeKey keyEnd)
{
return new SortedMapAVL<>(this.comparator, this.entrySet.headSet(new AbstractMap.SimpleEntry<>(keyEnd, null)));
}
@Override
public SortedMapAVL<TypeKey, TypeValue> tailMap(TypeKey keyStart)
{
return new SortedMapAVL<>(this.comparator, this.entrySet.tailSet(new AbstractMap.SimpleEntry<>(keyStart, null)));
}
public Entry<TypeKey, TypeValue> firstEntry()
{
return this.entrySet.first();
}
@Override
public TypeKey firstKey()
{
return firstEntry().getKey();
}
public Entry<TypeKey, TypeValue> lastEntry()
{
return this.entrySet.last();
}
@Override
public TypeKey lastKey()
{
return lastEntry().getKey();
}
@Override
public int size()
{
return this.entrySet().size();
}
@Override
public boolean isEmpty()
{
return this.entrySet.isEmpty();
}
@Override
public boolean containsKey(Object key)
{
return this.entrySet().contains(new AbstractMap.SimpleEntry<>((TypeKey) key, null));
}
@Override
public boolean containsValue(Object value)
{
throw new UnsupportedOperationException();
}
@Override
public TypeValue get(Object key)
{
Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>((TypeKey) key, null);
entry = this.entrySet.get(entry);
return entry == null ? null : entry.getValue();
}
@Override
public TypeValue put(TypeKey key, TypeValue value)
{
TypeValue result = get(key);
Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>(key, value);
this.entrySet().add(entry);
return result;
}
@Override
public TypeValue remove(Object key)
{
TypeValue result = get(key);
Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>((TypeKey) key, null);
this.entrySet.remove(entry);
return result;
}
@Override
public void putAll(Map<? extends TypeKey, ? extends TypeValue> map)
{
map.entrySet()
.forEach(entry -> put(entry.getKey(), entry.getValue()));
}
@Override
public void clear()
{
this.entrySet.clear();
}
@Override
public Set<TypeKey> keySet()
{
throw new UnsupportedOperationException();
}
@Override
public Collection<TypeValue> values()
{
return new Collection<TypeValue>()
{
@Override
public int size()
{
return SortedMapAVL.this.entrySet.size();
}
@Override
public boolean isEmpty()
{
return SortedMapAVL.this.entrySet.isEmpty();
}
@Override
public boolean contains(Object value)
{
throw new UnsupportedOperationException();
}
@Override
public Iterator<TypeValue> iterator()
{
return new Iterator<TypeValue>()
{
Iterator<Entry<TypeKey, TypeValue>> iterator = SortedMapAVL.this.entrySet.iterator();
@Override
public boolean hasNext()
{
return this.iterator.hasNext();
}
@Override
public TypeValue next()
{
return this.iterator.next().getValue();
}
};
}
@Override
public Object[] toArray()
{
throw new UnsupportedOperationException();
}
@Override
public <T> T[] toArray(T[] ts)
{
throw new UnsupportedOperationException();
}
@Override
public boolean add(TypeValue typeValue)
{
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o)
{
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(Collection<?> collection)
{
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends TypeValue> collection)
{
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> collection)
{
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> collection)
{
throw new UnsupportedOperationException();
}
@Override
public void clear()
{
throw new UnsupportedOperationException();
}
};
}
@Override
public SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet()
{
return this.entrySet;
}
@Override
public String toString()
{
return this.entrySet().toString();
}
}
public static class FIFO<Type>
{
public SingleLinkedList<Type> start;
public SingleLinkedList<Type> end;
public FIFO()
{
this.start = null;
this.end = null;
}
public boolean isEmpty()
{
return this.start == null;
}
public Type peek()
{
return this.start.element;
}
public Type pop()
{
Type result = this.start.element;
this.start = this.start.next;
return result;
}
public void push(Type element)
{
SingleLinkedList<Type> list = new SingleLinkedList<>(element, null);
if (this.start == null)
{
this.start = list;
this.end = list;
}
else
{
this.end.next = list;
this.end = list;
}
}
}
public static class MapCount<Type> extends SortedMapAVL<Type, Long>
{
private int count;
public MapCount(Comparator<? super Type> comparator)
{
super(comparator);
this.count = 0;
}
public long add(Type key, Long delta)
{
long result;
if (delta > 0)
{
Long value = get(key);
if (value == null)
{
value = delta;
}
else
{
value += delta;
}
put(key, value);
result = delta;
}
else
{
result = 0;
}
this.count += result;
return result;
}
public int count()
{
return this.count;
}
public List<Type> flatten()
{
List<Type> result = new ArrayList<>();
for (Entry<Type, Long> entry : entrySet())
{
for (long index = 0; index < entry.getValue(); index++)
{
result.add(entry.getKey());
}
}
return result;
}
@Override
public void putAll(Map<? extends Type, ? extends Long> map)
{
throw new UnsupportedOperationException();
}
@Override
public Long remove(Object key)
{
Long result = super.remove(key);
this.count -= result;
return result;
}
public long remove(Type key, Long delta)
{
long result;
if (delta > 0)
{
Long value = get(key) - delta;
if (value <= 0)
{
result = delta + value;
remove(key);
}
else
{
result = delta;
put(key, value);
}
}
else
{
result = 0;
}
this.count -= result;
return result;
}
@Override
public SortedMapAVL<Type, Long> subMap(Type keyStart, Type keyEnd)
{
throw new UnsupportedOperationException();
}
@Override
public SortedMapAVL<Type, Long> headMap(Type keyEnd)
{
throw new UnsupportedOperationException();
}
@Override
public SortedMapAVL<Type, Long> tailMap(Type keyStart)
{
throw new UnsupportedOperationException();
}
}
public static class MapSet<TypeKey, TypeValue> extends SortedMapAVL<TypeKey, SortedSetAVL<TypeValue>> implements Iterable<TypeValue>
{
private Comparator<? super TypeValue> comparatorValue;
public MapSet(Comparator<? super TypeKey> comparatorKey, Comparator<? super TypeValue> comparatorValue)
{
super(comparatorKey);
this.comparatorValue = comparatorValue;
}
public MapSet(Comparator<? super TypeKey> comparatorKey, SortedSetAVL<Entry<TypeKey, SortedSetAVL<TypeValue>>> entrySet, Comparator<? super TypeValue> comparatorValue)
{
super(comparatorKey, entrySet);
this.comparatorValue = comparatorValue;
}
public TypeValue firstValue()
{
TypeValue result;
Entry<TypeKey, SortedSetAVL<TypeValue>> firstEntry = firstEntry();
if (firstEntry == null)
{
result = null;
}
else
{
result = firstEntry.getValue().first();
}
return result;
}
public Iterator<TypeValue> iterator()
{
return new Iterator<TypeValue>()
{
Iterator<SortedSetAVL<TypeValue>> iteratorValues = values().iterator();
Iterator<TypeValue> iteratorValue = null;
@Override
public boolean hasNext()
{
return iteratorValues.hasNext() || (iteratorValue != null && iteratorValue.hasNext());
}
@Override
public TypeValue next()
{
if (iteratorValue == null || !iteratorValue.hasNext())
{
iteratorValue = iteratorValues.next().iterator();
}
return iteratorValue.next();
}
};
}
public TypeValue lastValue()
{
TypeValue result;
Entry<TypeKey, SortedSetAVL<TypeValue>> lastEntry = lastEntry();
if (lastEntry == null)
{
result = null;
}
else
{
result = lastEntry.getValue().last();
}
return result;
}
public boolean add(TypeKey key, TypeValue value)
{
SortedSetAVL<TypeValue> set = computeIfAbsent(key, k -> new SortedSetAVL<>(comparatorValue));
return set.add(value);
}
public boolean removeSet(TypeKey key, TypeValue value)
{
boolean result;
SortedSetAVL<TypeValue> set = get(key);
if (set == null)
{
result = false;
}
else
{
result = set.remove(value);
if (set.size() == 0)
{
remove(key);
}
}
return result;
}
@Override
public MapSet<TypeKey, TypeValue> headMap(TypeKey keyEnd)
{
return new MapSet<>(this.comparator, this.entrySet.headSet(new AbstractMap.SimpleEntry<>(keyEnd, null)), this.comparatorValue);
}
@Override
public MapSet<TypeKey, TypeValue> tailMap(TypeKey keyStart)
{
return new MapSet<>(this.comparator, this.entrySet.tailSet(new AbstractMap.SimpleEntry<>(keyStart, null)), this.comparatorValue);
}
}
static class IteratorBuffer<Type>
{
private Iterator<Type> iterator;
private List<Type> list;
public IteratorBuffer(Iterator<Type> iterator)
{
this.iterator = iterator;
this.list = new ArrayList<Type>();
}
public Iterator<Type> iterator()
{
return new Iterator<Type>()
{
int index = 0;
@Override
public boolean hasNext()
{
return this.index < list.size() || iterator().hasNext();
}
@Override
public Type next()
{
if (list.size() <= this.index)
{
list.add(iterator.next());
}
Type result = list.get(index);
index += 1;
return result;
}
};
}
}
public static <Type> List<List<Type>> permutations(List<Type> list)
{
List<List<Type>> result = new ArrayList<>();
result.add(new ArrayList<>());
for (Type element : list)
{
List<List<Type>> permutations = result;
result = new ArrayList<>();
for (List<Type> permutation : permutations)
{
for (int index = 0; index <= permutation.size(); index++)
{
List<Type> permutationNew = new ArrayList<>(permutation);
permutationNew.add(index, element);
result.add(permutationNew);
}
}
}
return result;
}
public static List<List<Integer>> combinations(int n, int k)
{
List<List<Integer>> result = new ArrayList<>();
if (k == 0)
{
}
else
{
if (k == 1)
{
List<Integer> combination = new ArrayList<>();
combination.add(n);
result.add(combination);
}
else
{
for (int index = 0; index <= n; index++)
{
for (List<Integer> combination : combinations(n - index, k - 1))
{
combination.add(index);
result.add(combination);
}
}
}
}
return result;
}
public static <Type> int compare(Iterator<Type> iterator0, Iterator<Type> iterator1, Comparator<Type> comparator)
{
int result = 0;
while (result == 0 && iterator0.hasNext() && iterator1.hasNext())
{
result = comparator.compare(iterator0.next(), iterator1.next());
}
if (result == 0)
{
if (iterator1.hasNext())
{
result = -1;
}
else
{
if (iterator0.hasNext())
{
result = 1;
}
}
}
return result;
}
public static <Type> int compare(Iterable<Type> iterable0, Iterable<Type> iterable1, Comparator<Type> comparator)
{
return compare(iterable0.iterator(), iterable1.iterator(), comparator);
}
private static String nextString() throws IOException
{
while ((stringTokenizer == null) || (!stringTokenizer.hasMoreTokens()))
{
stringTokenizer = new StringTokenizer(bufferedReader.readLine());
}
return stringTokenizer.nextToken();
}
private static String[] nextStrings(int n) throws IOException
{
String[] result = new String[n];
{
for (int index = 0; index < n; index++)
{
result[index] = nextString();
}
}
return result;
}
public static int nextInt() throws IOException
{
return Integer.parseInt(nextString());
}
public static int[] nextInts(int n) throws IOException
{
int[] result = new int[n];
nextInts(n, result);
return result;
}
public static void nextInts(int n, int[]... result) throws IOException
{
for (int index = 0; index < n; index++)
{
for (int value = 0; value < result.length; value++)
{
result[value][index] = nextInt();
}
}
}
public static double nextDouble() throws IOException
{
return Double.parseDouble(nextString());
}
public static long nextLong() throws IOException
{
return Long.parseLong(nextString());
}
public static long[] nextLongs(int n) throws IOException
{
long[] result = new long[n];
{
for (int index = 0; index < n; index++)
{
result[index] = nextLong();
}
}
return result;
}
public static String nextLine() throws IOException
{
return bufferedReader.readLine();
}
public static void close()
{
out.close();
}
public static int binarySearchMinimum(Function<Integer, Boolean> filter, int start, int end)
{
int result;
if (start == end)
{
result = end;
}
else
{
int middle = start + (end - start) / 2;
if (filter.apply(middle))
{
result = binarySearchMinimum(filter, start, middle);
}
else
{
result = binarySearchMinimum(filter, middle + 1, end);
}
}
return result;
}
public static int binarySearchMaximum(Function<Integer, Boolean> filter, int start, int end)
{
return -binarySearchMinimum(x -> filter.apply(-x), -end, -start);
}
public static long divideCeil(long x, long y)
{
return (x + y - 1) / y;
}
public static Set<Long> divisors(long n)
{
SortedSetAVL<Long> result = new SortedSetAVL<>(Comparator.naturalOrder());
result.add(1L);
for (Long factor : factors(n))
{
SortedSetAVL<Long> divisors = new SortedSetAVL<>(result);
for (Long divisor : result)
{
divisors.add(divisor * factor);
}
result = divisors;
}
return result;
}
public static long faculty(int n)
{
long result = 1;
for (int index = 2; index <= n; index++)
{
result *= index;
}
return result;
}
public static LinkedList<Long> factors(long n)
{
LinkedList<Long> result = new LinkedList<>();
Iterator<Long> primes = ITERATOR_BUFFER_PRIME.iterator();
Long prime;
while (n > 1 && (prime = primes.next()) * prime <= n)
{
while (n % prime == 0)
{
result.add(prime);
n /= prime;
}
}
if (n > 1)
{
result.add(n);
}
return result;
}
public static long gcd(long a, long b)
{
while (a != 0 && b != 0)
{
if (a > b)
{
a %= b;
}
else
{
b %= a;
}
}
return a + b;
}
public static long[] generatePOWER2()
{
long[] result = new long[63];
for (int x = 0; x < result.length; x++)
{
result[x] = 1L << x;
}
return result;
}
public static boolean isPrime(long x)
{
boolean result = x > 1;
Iterator<Long> iterator = ITERATOR_BUFFER_PRIME.iterator();
Long prime;
while ((prime = iterator.next()) * prime <= x)
{
result &= x % prime > 0;
}
return result;
}
public static long knapsack(List<Tuple3<Long, Integer, Integer>> itemsValueWeightCount, int weightMaximum)
{
long[] valuesMaximum = new long[weightMaximum + 1];
for (Tuple3<Long, Integer, Integer> itemValueWeightCount : itemsValueWeightCount)
{
long itemValue = itemValueWeightCount.v0;
int itemWeight = itemValueWeightCount.v1;
int itemCount = itemValueWeightCount.v2;
for (int weight = weightMaximum; 0 <= weight; weight--)
{
for (int index = 1; index <= itemCount && 0 <= weight - index * itemWeight; index++)
{
valuesMaximum[weight] = Math.max(valuesMaximum[weight], valuesMaximum[weight - index * itemWeight] + index * itemValue);
}
}
}
long result = 0;
for (long valueMaximum : valuesMaximum)
{
result = Math.max(result, valueMaximum);
}
return result;
}
public static boolean knapsackPossible(List<Tuple2<Integer, Integer>> itemsWeightCount, int weightMaximum)
{
boolean[] weightPossible = new boolean[weightMaximum + 1];
weightPossible[0] = true;
int weightLargest = 0;
for (Tuple2<Integer, Integer> itemWeightCount : itemsWeightCount)
{
int itemWeight = itemWeightCount.v0;
int itemCount = itemWeightCount.v1;
for (int weightStart = 0; weightStart < itemWeight; weightStart++)
{
int count = 0;
for (int weight = weightStart; weight <= weightMaximum && (0 < count || weight <= weightLargest); weight += itemWeight)
{
if (weightPossible[weight])
{
count = itemCount;
}
else
{
if (0 < count)
{
weightPossible[weight] = true;
weightLargest = weight;
count -= 1;
}
}
}
}
}
return weightPossible[weightMaximum];
}
public static long lcm(int a, int b)
{
return a * b / gcd(a, b);
}
public static <T> List<T> permutation(long p, List<T> x)
{
List<T> copy = new ArrayList<>();
for (int index = 0; index < x.size(); index++)
{
copy.add(x.get(index));
}
List<T> result = new ArrayList<>();
for (int indexTo = 0; indexTo < x.size(); indexTo++)
{
int indexFrom = (int) p % copy.size();
p = p / copy.size();
result.add(copy.remove(indexFrom));
}
return result;
}
public static <Type> String toString(Iterator<Type> iterator, String separator)
{
StringBuilder stringBuilder = new StringBuilder();
if (iterator.hasNext())
{
stringBuilder.append(iterator.next());
}
while (iterator.hasNext())
{
stringBuilder.append(separator);
stringBuilder.append(iterator.next());
}
return stringBuilder.toString();
}
public static <Type> String toString(Iterator<Type> iterator)
{
return toString(iterator, " ");
}
public static <Type> String toString(Iterable<Type> iterable, String separator)
{
return toString(iterable.iterator(), separator);
}
public static <Type> String toString(Iterable<Type> iterable)
{
return toString(iterable, " ");
}
public static Stream<BigInteger> streamFibonacci()
{
return Stream.generate(new Supplier<BigInteger>()
{
private BigInteger n0 = BigInteger.ZERO;
private BigInteger n1 = BigInteger.ONE;
@Override
public BigInteger get()
{
BigInteger result = n0;
n0 = n1;
n1 = result.add(n0);
return result;
}
});
}
public static Stream<Long> streamPrime(int sieveSize)
{
return Stream.generate(new Supplier<Long>()
{
private boolean[] isPrime = new boolean[sieveSize];
private long sieveOffset = 2;
private List<Long> primes = new ArrayList<>();
private int index = 0;
public void filter(long prime, boolean[] result)
{
if (prime * prime < this.sieveOffset + sieveSize)
{
long remainingStart = this.sieveOffset % prime;
long start = remainingStart == 0 ? 0 : prime - remainingStart;
for (long index = start; index < sieveSize; index += prime)
{
result[(int) index] = false;
}
}
}
public void generatePrimes()
{
Arrays.fill(this.isPrime, true);
this.primes.forEach(prime -> filter(prime, isPrime));
for (int index = 0; index < sieveSize; index++)
{
if (isPrime[index])
{
this.primes.add(this.sieveOffset + index);
filter(this.sieveOffset + index, isPrime);
}
}
this.sieveOffset += sieveSize;
}
@Override
public Long get()
{
while (this.primes.size() <= this.index)
{
generatePrimes();
}
Long result = this.primes.get(this.index);
this.index += 1;
return result;
}
});
}
public static long totient(long n)
{
Set<Long> factors = new SortedSetAVL<>(factors(n), Comparator.naturalOrder());
long result = n;
for (long p : factors)
{
result -= result / p;
}
return result;
}
public static void main(String[] args)
{
try
{
solve();
} catch (IOException exception)
{
exception.printStackTrace();
}
close();
}
public static class Flight
{
public static final Comparator COMPARATOR = Comparator
.comparing(Flight::getDay)
.thenComparing(Flight::getCity)
.thenComparing(Flight::getCost);
public final int day;
public final int city;
public final int cost;
public Flight(int day, int city, int cost)
{
this.day = day;
this.city = city;
this.cost = cost;
}
public int getDay()
{
return day;
}
public int getCity()
{
return city;
}
public int getCost()
{
return cost;
}
}
public static void travel(SortedSet<Flight> flights, int n, Long[] day2TotalCost)
{
Integer[] member2Cost = new Integer[n];
long count = 0;
long totalCost = 0;
for (Flight flight : flights)
{
if (member2Cost[flight.city] == null)
{
count += 1;
member2Cost[flight.city] = flight.cost;
}
else
{
totalCost -= member2Cost[flight.city];
member2Cost[flight.city] = Math.min(member2Cost[flight.city], flight.cost);
}
totalCost += member2Cost[flight.city];
if (count == member2Cost.length)
{
day2TotalCost[flight.day] = totalCost;
}
}
}
public static void fillInbound(Long[] day2TotalCost)
{
Long totalCost = null;
for (int index = 0; index < day2TotalCost.length; index++)
{
if (day2TotalCost[index] == null)
{
day2TotalCost[index] = totalCost;
}
else
{
totalCost = day2TotalCost[index];
}
}
}
public static void fillOutbound(Long[] day2TotalCost)
{
Long totalCost = null;
for (int index = day2TotalCost.length - 1; 0 <= index; index--)
{
if (day2TotalCost[index] == null)
{
day2TotalCost[index] = totalCost;
}
else
{
totalCost = day2TotalCost[index];
}
}
}
public static long solve(int n, int m, int k, int[] d, int[] f, int[] t, int[] c)
{
SortedSet<Flight> inbound = new SortedSetAVL<>(Flight.COMPARATOR);
SortedSet<Flight> outbound = new SortedSetAVL<>(Flight.COMPARATOR.reversed());
for (int index = 0; index < m; index++)
{
int day = d[index] - 1;
int from = f[index] - 1;
int to = t[index] - 1;
int cost = c[index];
if (from == -1)
{
outbound.add(new Flight(day, to, cost));
}
else
{
inbound.add(new Flight(day, from, cost));
}
}
int days;
if (inbound.isEmpty() || outbound.isEmpty())
{
days = 0;
}
else
{
days = Math.max(inbound.last().day, outbound.first().day) + 1;
}
Long[] day2TotalCostInbound = new Long[days];
travel(inbound, n, day2TotalCostInbound);
fillInbound(day2TotalCostInbound);
Long[] day2TotalCostOutbound = new Long[days];
travel(outbound, n, day2TotalCostOutbound);
fillOutbound(day2TotalCostOutbound);
long result = -1;
for (int index = 0; index < days - k - 1; index++)
{
Long costInbound = day2TotalCostInbound[index];
Long costOutbound = day2TotalCostOutbound[index + k + 1];
if (costInbound != null && costOutbound != null)
{
if (result == -1)
{
result = costInbound + costOutbound;
}
else
{
result = Math.min(result, costInbound + costOutbound);
}
}
}
return result;
}
public static void solve() throws IOException
{
int n = nextInt();
int m = nextInt();
int k = nextInt();
int[] d = new int[m];
int[] f = new int[m];
int[] t = new int[m];
int[] c = new int[m];
nextInts(m, d, f, t, c);
out.println(solve(n, m, k, d, f, t, c));
}
} | JAVA |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
struct Flight {
long long d, f, t, c;
};
const int MAXN = 1e5;
int n, m, k;
Flight p[MAXN + 1];
multiset<long long> mnl[MAXN + 1], mnr[MAXN + 1];
int main() {
scanf("%d%d%d", &n, &m, &k);
for (int i = 1; i <= m; i++) {
scanf("%lld%lld%lld%lld", &p[i].d, &p[i].f, &p[i].t, &p[i].c);
}
sort(p + 1, p + m + 1,
[&](const Flight& a, const Flight& b) { return a.d < b.d; });
for (int i = 1; i <= m; i++) {
if (p[i].f == 0) mnr[p[i].t].insert(p[i].c);
}
long long lcost = 0, rcost = 0;
for (int i = 1; i <= n; i++) {
if (mnr[i].empty()) {
puts("-1");
return 0;
}
rcost += *mnr[i].begin();
}
int l = 1, r = 1;
int lCount = 0;
long long res = 1e18;
for (int day = 1;; day++) {
bool flag = 1;
while (r <= m && p[r].d < day + k + 1) {
if (p[r].f == 0) {
rcost -= *mnr[p[r].t].begin();
auto it = mnr[p[r].t].find(p[r].c);
mnr[p[r].t].erase(it);
if (mnr[p[r].t].empty()) {
flag = 0;
break;
}
rcost += *mnr[p[r].t].begin();
}
r++;
}
if (!flag) break;
while (l <= m && p[l].d <= day) {
if (p[l].t == 0) {
if (mnl[p[l].f].empty())
lCount++;
else
lcost -= *mnl[p[l].f].begin();
mnl[p[l].f].insert(p[l].c);
lcost += *mnl[p[l].f].begin();
}
l++;
}
if (lCount == n) res = min(res, lcost + rcost);
}
printf("%lld", res == 1e18 ? -1 : res);
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
const int MAXINT = 2147483640;
const long long MAXLL = 9223372036854775800LL;
const long long MAXN = 1123456;
using namespace std;
pair<pair<long long, long long>, pair<long long, long long> > a[MAXN];
vector<long long> v[2][MAXN];
set<pair<long long, long long> > S[MAXN];
long long kol[2], c[2][MAXN], num[2][MAXN], s[MAXN];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
srand(time(0));
long long n, m, k, i, j, z, d, r0, r1, l1, ans = MAXLL, sum = 0;
cin >> n >> m >> k;
for (i = 1; i <= m; i++) {
cin >> a[i].first.first >> a[i].second.first >> a[i].second.second >>
a[i].first.second;
if (!a[i].second.first) a[i].second.first = 1;
if (!a[i].second.second)
a[i].second.second = a[i].second.first, a[i].second.first = 0;
}
sort(a + 1, a + m + 1);
kol[0] = n;
kol[1] = n;
r0 = r1 = 1;
l1 = 1;
while (r1 <= m) {
if (a[r1].second.first == 1) {
if (c[1][a[r1].second.second] == 0) --kol[1];
sum -= c[1][a[r1].second.second];
S[a[r1].second.second].insert(make_pair(a[r1].first.second, r1));
c[1][a[r1].second.second] = S[a[r1].second.second].begin()->first;
sum += c[1][a[r1].second.second];
}
++r1;
}
for (d = 1; d <= 10000000; d++) {
while (a[r0].first.first == d && r0 <= m) {
if (a[r0].second.first == 0) {
if (c[0][a[r0].second.second] == 0) --kol[0];
sum -= c[0][a[r0].second.second];
s[a[r0].second.second] =
min(s[a[r0].second.second], a[r0].first.second);
if (s[a[r0].second.second] == 0)
s[a[r0].second.second] = a[r0].first.second;
c[0][a[r0].second.second] = s[a[r0].second.second];
sum += c[0][a[r0].second.second];
}
++r0;
}
while (a[l1].first.first <= d + k && l1 <= m) {
if (a[l1].second.first == 1) {
S[a[l1].second.second].erase(make_pair(a[l1].first.second, l1));
sum -= c[1][a[l1].second.second];
if (S[a[l1].second.second].size() == 0)
++kol[1];
else {
c[1][a[l1].second.second] = S[a[l1].second.second].begin()->first;
sum += c[1][a[l1].second.second];
}
}
++l1;
}
if (kol[0] + kol[1] == 0) ans = min(ans, sum);
if (r1 > m && r0 > m) break;
}
if (ans == MAXLL) ans = -1;
cout << ans << "\n";
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 8;
struct data {
int s, f;
long long c;
};
long long l[N], r[N], nl[N], nr[N];
long long Min[N];
vector<data> day[N];
int trv[N];
int main() {
int n, m, k;
scanf("%d %d %d", &n, &m, &k);
int M = 0;
for (int i = 1; i <= m; i++) {
int d;
data p;
scanf("%d %d %d %lld", &d, &p.s, &p.f, &p.c);
M = max(M, d);
day[d].push_back(p);
}
long long res = 1e18;
for (int i = 1; i <= M; i++) {
for (int ii = 0; ii < day[i].size(); ii++) {
data p = day[i][ii];
if (p.s != 0) {
if (trv[p.s] != 1) {
trv[p.s] = 1;
nl[i]++;
l[i] += p.c;
Min[p.s] = p.c;
} else {
if (Min[p.s] > p.c) {
l[i] += p.c - Min[p.s];
Min[p.s] = p.c;
}
}
}
}
l[i] += l[i - 1];
nl[i] += nl[i - 1];
}
for (int i = M; i >= 1; i--) {
for (int ii = 0; ii < day[i].size(); ii++) {
data p = day[i][ii];
if (p.s == 0) {
if (trv[p.f] != 2) {
trv[p.f] = 2;
nr[i]++;
r[i] += p.c;
Min[p.f] = p.c;
} else {
if (Min[p.f] > p.c) {
r[i] += p.c - Min[p.f];
Min[p.f] = p.c;
}
}
}
}
r[i] += r[i + 1];
nr[i] += nr[i + 1];
}
for (int i = 1; i <= M; i++) {
if (i + k + 1 > M) break;
if (nl[i] == nr[i + k + 1] and nl[i] == n) {
res = min(res, l[i] + r[i + k + 1]);
}
}
if (res < 1e18)
cout << res;
else
cout << -1;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int intinf = 1e9;
const long long inf = 1e18;
const int N = 1e5 + 5;
const int M = 1e6 + 5;
int n;
vector<pair<int, int>> out[N], in[N];
vector<int> suf[N], pref[N];
vector<pair<int, int>> q[M];
int getbest(int i, int l, int r) {
int res1;
int l1 = 0;
int r1 = in[i].size() - 1;
if (r1 == -1) {
return intinf;
}
while (r1 - l1 > 1) {
int m = (l1 + r1) / 2;
if (in[i][m].first > l) {
r1 = m - 1;
} else {
l1 = m;
}
}
if (in[i][r1].first <= l) {
res1 = pref[i][r1];
} else if (in[i][l1].first <= l) {
res1 = pref[i][l1];
} else {
return intinf;
}
int l2 = 0;
int r2 = out[i].size() - 1;
if (r2 == -1) {
return intinf;
}
while (r2 - l2 > 1) {
int m = (l2 + r2) / 2;
if (out[i][m].first < r) {
l2 = m + 1;
} else {
r2 = m;
}
}
if (out[i][l2].first >= r) {
return res1 + suf[i][l2];
} else if (out[i][r2].first >= r) {
return res1 + suf[i][r2];
} else {
return intinf;
}
}
long long sum = 0;
map<int, int> can;
void upd(int p, int l, int r) {
for (int i = 0; i < q[p].size(); i++) {
int f = q[p][i].first;
int t = q[p][i].second;
if (f == 0) {
if (can.count(t)) {
sum -= can[t];
}
can[t] = getbest(t, l, r);
if (can[t] == intinf) {
can.erase(t);
} else {
sum += can[t];
}
} else if (t == 0) {
if (can.count(f)) {
sum -= can[f];
}
can[f] = getbest(f, l, r);
if (can[f] == intinf) {
can.erase(f);
} else {
sum += can[f];
}
}
}
}
long long get(int l, int r) {
upd(l, l, r);
upd(r - 1, l, r);
if (can.size() == n) {
return sum;
} else {
return inf;
}
}
long long brute(int l, int r) {
bool ok = true;
for (int i = 1; i <= n; i++) {
int first = getbest(i, l, r);
if (first == intinf) {
ok = 0;
} else {
can[i] = first;
sum += first;
}
}
if (!ok) {
return inf;
} else {
return sum;
}
}
int main() {
cin.tie(0);
ios_base::sync_with_stdio(0);
int m, k;
cin >> n >> m >> k;
int mx = 0;
for (int i = 0; i < m; i++) {
int d, f, t, c;
cin >> d >> f >> t >> c;
mx = max(mx, d);
if (f == 0) {
out[t].push_back({d, c});
} else if (t == 0) {
in[f].push_back({d, c});
}
q[d].push_back({f, t});
}
for (int i = 1; i <= n; i++) {
sort((in[i]).begin(), (in[i]).end());
pref[i].resize(in[i].size());
for (int j = 0; j < pref[i].size(); j++) {
pref[i][j] = min(j == 0 ? intinf : pref[i][j - 1], in[i][j].second);
}
sort((out[i]).begin(), (out[i]).end());
suf[i].resize(out[i].size());
for (int j = suf[i].size() - 1; j >= 0; j--) {
suf[i][j] = min(j == suf[i].size() - 1 ? intinf : suf[i][j + 1],
out[i][j].second);
}
}
long long ans = inf;
for (int l = 2; l <= mx - k; l++) {
if (l == 2) {
ans = brute(l - 1, l + k);
} else {
ans = min(ans, get(l - 1, l + k));
}
}
if (ans == inf) {
ans = -1;
}
cout << ans;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
template <class T>
T sqr(T x) {
return x * x;
}
template <class T>
T gcd(T a, T b) {
return (b != 0 ? gcd<T>(b, a % b) : a);
}
template <class T>
T lcm(T a, T b) {
return (a / gcd<T>(a, b) * b);
}
template <class T>
inline T bigmod(T p, T e, T M) {
if (e == 0) return 1;
if (e % 2 == 0) {
long long int t = bigmod(p, e / 2, M);
return (T)((t * t) % M);
}
return (T)((long long int)bigmod(p, e - 1, M) * (long long int)p) % M;
}
template <class T>
inline T bigexp(T p, T e) {
if (e == 0) return 1;
if (e % 2 == 0) {
long long int t = bigexp(p, e / 2);
return (T)((t * t));
}
return (T)((long long int)bigexp(p, e - 1) * (long long int)p);
}
template <class T>
inline T modinverse(T a, T M) {
return bigmod(a, M - 2, M);
}
int dx4[] = {1, 0, -1, 0};
int dy4[] = {0, 1, 0, -1};
int dx8[] = {1, 1, 0, -1, -1, -1, 0, 1};
int dy8[] = {0, 1, 1, 1, 0, -1, -1, -1};
int nx8[] = {1, 1, -1, -1, 2, 2, -2, -2};
int ny8[] = {2, -2, 2, -2, 1, -1, 1, -1};
int month[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int n, m, k, d, bl[1000005], blr[1000005], don, donr;
long long int f[1000005], r[1000005], cum[1000005], cumr[1000005], tot;
struct T {
int u, v, w;
};
T a;
vector<T> v[1000005];
int main() {
cin >> n >> m;
scanf("%d", &k);
for (__typeof(n) i = (1); i <= (n); i++) bl[i] = blr[i] = 10000000;
for (__typeof(1000001) i = (0); i <= (1000001); i++)
cum[i] = 1000000000000000000LL, cumr[i] = 1000000000000000000LL;
for (__typeof(m) i = (1); i <= (m); i++) {
scanf("%d", &d);
scanf("%d %d", &a.u, &a.v);
scanf("%d", &a.w);
v[d].push_back(a);
}
for (int i = 1; i <= 1000000; i++) {
for (int j = 0; j < (int)v[i].size(); j++) {
a = v[i][j];
if (a.u != 0) {
if (bl[a.u] == 1e7) don++;
if (bl[a.u] > a.w) {
if (bl[a.u] != 1e7) tot -= bl[a.u];
bl[a.u] = a.w;
tot += bl[a.u];
}
}
}
if (don >= n) {
f[i] = tot;
cum[i] = f[i];
}
cum[i] = min(cum[i], cum[i - 1]);
}
tot = 0;
for (int i = 1000000; i >= 1; i--) {
for (int j = 0; j < (int)v[i].size(); j++) {
a = v[i][j];
if (a.u == 0) {
if (blr[a.v] == 1e7) donr++;
if (blr[a.v] > a.w) {
if (blr[a.v] != 1e7) tot -= blr[a.v];
blr[a.v] = a.w;
tot += blr[a.v];
}
}
}
if (donr >= n) {
r[i] = tot;
cumr[i] = r[i];
}
cumr[i] = min(cumr[i], cumr[i + 1]);
}
tot = 1000000000000000000LL;
for (int i = 1; i <= 1000000; i++) {
if (i + k + 1 <= 1000000) {
tot = min(tot, cum[i] + cumr[i + k + 1]);
}
}
if (tot >= 1000000000000000000LL) tot = -1;
cout << tot, printf("\n");
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:16777216")
using namespace std;
const int inf = (int)1e9 + 5;
const long long MAXN = 300005;
const long long MAXVAL = 10000000;
const long long INF = (long long)1e18 + 50;
const long long MOD = (long long)1e9 + 7;
const unsigned long long HASH_MOD = 2305843009213693951;
string failMessage;
void fail(string addedMessage = "") {
cout << failMessage;
if (addedMessage != "") {
(void)0;
(void)0;
}
exit(0);
};
struct flight {
long long day, v, to, cost;
};
bool comp(flight a, flight b) { return a.day < b.day; }
void solve() {
long long n, m, k;
cin >> n >> m >> k;
vector<flight> a(m);
long long d, v, t, c;
for (long long i = 0; i < m; i++) {
cin >> d >> v >> t >> c;
a[i] = {d, v, t, c};
}
sort(a.begin(), a.end(), comp);
long long countToMegapolis = 0;
vector<long long> toMegapolis(n + 1, -1);
vector<set<pair<long long, long long>>> fromMegapolis(n + 1);
long long r = 0;
for (long long i = 0; i < m; i++) {
d = a[i].day;
v = a[i].v;
t = a[i].to;
c = a[i].cost;
if (v != 0) continue;
fromMegapolis[t].insert({c, d});
}
long long ans = INF;
long long cur = 0;
failMessage = "-1";
for (long long i = 1; i <= n; i++) {
if (fromMegapolis[i].size() == 0) fail();
cur += fromMegapolis[i].begin()->first;
}
for (long long i = 0; i < m; i++) {
d = a[i].day;
v = a[i].v;
t = a[i].to;
c = a[i].cost;
if (t == 0) {
if (toMegapolis[v] == -1) {
countToMegapolis++;
toMegapolis[v] = c;
cur += c;
}
if (c < toMegapolis[v]) {
cur -= (toMegapolis[v] - c);
toMegapolis[v] = c;
}
}
bool isGood = true;
while (r < m && a[r].day <= d + k) {
if (a[r].v == 0) {
cur -= fromMegapolis[a[r].to].begin()->first;
fromMegapolis[a[r].to].erase({a[r].cost, a[r].day});
if (fromMegapolis[a[r].to].size() == 0) {
isGood = false;
break;
}
cur += fromMegapolis[a[r].to].begin()->first;
}
r++;
}
if (!isGood) break;
if (countToMegapolis == n) ans = min(ans, cur);
}
if (ans == INF) ans = -1;
cout << ans;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.precision(15);
solve();
(void)0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
using namespace std;
long long powm(long long base, long long exp, long long mod = 1000000007) {
long long ans = 1;
while (exp) {
if (exp & 1) ans = (ans * base) % mod;
exp >>= 1, base = (base * base) % mod;
}
return ans;
}
long long pref[2000005], suff[2000005];
long long arr1[100005], arr2[100005];
vector<pair<pair<long long, long long>, long long>> v1, v2;
int main() {
long long n, m, k, d, first, t, c;
cin >> n >> m >> k;
while (m--) {
cin >> d >> first >> t >> c;
if (first == 0)
v2.push_back(make_pair(make_pair(d, t), c));
else
v1.push_back(make_pair(make_pair(d, first), c));
}
sort((v1).begin(), (v1).end());
sort((v2).begin(), (v2).end());
reverse((v2).begin(), (v2).end());
long long cnt1 = 0, cnt2 = 0, curr1 = 0, curr2 = 0;
for (long long i = 0; i < 100005; i++)
arr1[i] = arr2[i] = 1000111000111000111LL;
for (long long i = 0; i < 2000005; i++)
pref[i] = suff[i] = 1000111000111000111LL;
for (auto i : v1) {
if (arr1[i.first.second] == 1000111000111000111LL) {
arr1[i.first.second] = i.second;
curr1 += i.second;
cnt1++;
} else {
curr1 -= arr1[i.first.second];
arr1[i.first.second] = min(arr1[i.first.second], i.second);
curr1 += arr1[i.first.second];
}
if (cnt1 == n) pref[i.first.first] = min(pref[i.first.first], curr1);
}
for (auto i : v2) {
if (arr2[i.first.second] == 1000111000111000111LL) {
arr2[i.first.second] = i.second;
curr2 += i.second;
cnt2++;
} else {
curr2 -= arr2[i.first.second];
arr2[i.first.second] = min(arr2[i.first.second], i.second);
curr2 += arr2[i.first.second];
}
if (cnt2 == n) suff[i.first.first] = min(suff[i.first.first], curr2);
}
for (long long i = 1; i < 2000005; i++) pref[i] = min(pref[i - 1], pref[i]);
for (long long i = 2000005 - 2; i >= 0; i--)
suff[i] = min(suff[i + 1], suff[i]);
long long ret = 1000111000111000111LL;
for (long long i = 1; i < 2000005; i++) {
if (i + k < 2000005) ret = min(ret, pref[i - 1] + suff[i + k]);
}
if (ret == 1000111000111000111LL)
cout << -1;
else
cout << ret;
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | N,M,K = map(int,input().split())
INF = 10**6+1
from collections import defaultdict
incoming = defaultdict(list)
outgoing = defaultdict(list)
for _ in range(M):
d,f,t,c = map(int,input().split())
if t == 0:
incoming[d].append((c,f-1))
if f == 0:
outgoing[d].append((c,t-1))
incoming_dates = sorted(incoming.keys())
outgoing_dates = sorted(outgoing.keys(),reverse=True)
Li = []
mark = [False]*N
cnt = 0
costs = [0]*N
total_cost = 0
for d in incoming_dates:
for c,x in incoming[d]:
if mark[x]:
if costs[x] > c:
total_cost += c-costs[x]
costs[x] = c
else:
mark[x] = True
cnt += 1
costs[x] = c
total_cost += c
if cnt == N:
Li.append((d,total_cost))
Lo = []
mark = [False]*N
cnt = 0
costs = [0]*N
total_cost = 0
for d in outgoing_dates:
for c,x in outgoing[d]:
if mark[x]:
if costs[x] > c:
total_cost += c-costs[x]
costs[x] = c
else:
mark[x] = True
cnt += 1
costs[x] = c
total_cost += c
if cnt == N:
Lo.append((d,total_cost))
Lo.reverse()
if not Li or not Lo:
print(-1)
exit()
# print(Li,Lo)
from bisect import bisect
best = float('inf')
for d,c in Li:
i = bisect(Lo,(d+K+1,0))
if i >= len(Lo):
break
else:
best = min(best,c+Lo[i][1])
if best == float('inf'):
print(-1)
else:
print(best) | PYTHON3 |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | /**
* Created by Aminul on 9/6/2017.
*/
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
public class CF85D_3 {
public static int index;
public static void main(String[] args)throws Exception {
InputReader in = new InputReader(System.in);
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
int n = in.nextInt(), m = in.nextInt(), k = in.nextInt();
long inf = (long)1e12;
int maxN = (int)1e6;
List<Node> list[] = new List[maxN+1];
for(int i = 0; i <= maxN; i++){
list[i] = new ArrayList<>();
}
for(int i = 1; i <= m; i++){
int d = in.nextInt(), f = in.nextInt(), t = in.nextInt(), c = in.nextInt();
list[d].add(new Node(d, f, t, c));
}
long totalSum = 0;
int totalN = 0;
long pre[] = new long[maxN+1];
long suf[] = new long[maxN+1];
int preN[] = new int[maxN+1];
int sufN[] = new int[maxN+1];
long[] min = new long[maxN+1];
Arrays.fill(min, inf);
for(int i = 1; i <= maxN; i++){
for(Node node : list[i]){
if(node.t == 0){
if(min[node.f] > node.c){
if(min[node.f] == inf){
totalN++;
min[node.f] = 0;
}
totalSum -= min[node.f];
min[node.f] = node.c;
totalSum += min[node.f];
}
}
}
preN[i] = totalN;
pre[i] = totalSum;
}
Arrays.fill(min, inf);
totalN = 0; totalSum = 0;
for(int i = maxN; i >= 1; i--){
for(Node node : list[i]){
if(node.f == 0){
if(min[node.t] > node.c){
if(min[node.t] == inf){
totalN++;
min[node.t] = 0;
}
totalSum -= min[node.t];
min[node.t] = node.c;
totalSum += min[node.t];
}
}
}
sufN[i] = totalN;
suf[i] = totalSum;
}
boolean ok = true;
long ans = inf;
for(int i = 1, j = i+k+1; j <= maxN; i++, j++){
if(preN[i] == n && sufN[j] == n){
ans = Math.min(pre[i] + suf[j], ans);
}
}
if(ans == inf) ans = -1;
pw.println(ans);
pw.close();
}
static class Node implements Comparable<Node>{
int d, f, t;
long c;
Node(int D, int F, int T, long C){
d = D; f = F; t = T; c = C;
}
public int compareTo(Node node){
return d - node.d;
}
public String toString(){
return d+" "+f+" "+t+" "+c;
}
}
static void debug(Object...obj) {
System.err.println(Arrays.deepToString(obj));
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
//InputReader in = new InputReader(new FileReader("File_Name"));
public InputReader(FileReader file) {
reader = new BufferedReader(file);
tokenizer = null;
}
public String next() {
try {
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
return null;
}
return tokenizer.nextToken();
}
public String nextLine() {
String line = null;
try {
tokenizer = null;
line = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public boolean hasNext(){
try {
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(reader.readLine());
}
catch (Exception e) {
return false;
}
return true;
}
}
} | JAVA |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int MAX = 1e6 + 10;
int n, m, k, sum1, sum2;
long long st[MAX], en[MAX];
int amin[MAX], bmin[MAX];
struct node {
int d;
int f;
int t;
int v;
} a[MAX], b[MAX];
bool cmp1(node x, node y) { return x.d < y.d; }
bool cmp2(node x, node y) { return x.d > y.d; }
int main() {
scanf("%d%d%d", &n, &m, &k);
memset(st, 0, sizeof(st));
memset(en, 0, sizeof(en));
memset(amin, 0, sizeof(amin));
memset(bmin, 0, sizeof(bmin));
sum1 = 0, sum2 = 0;
int max1 = 0;
for (int i = 1; i <= m; i++) {
int dd, ff, tt, vv;
scanf("%d%d%d%d", &dd, &ff, &tt, &vv);
max1 = max(max1, dd);
if (tt == 0) {
sum1++;
a[sum1].d = dd;
a[sum1].f = ff;
a[sum1].t = tt;
a[sum1].v = vv;
} else {
sum2++;
b[sum2].d = dd;
b[sum2].f = ff;
b[sum2].t = tt;
b[sum2].v = vv;
}
}
sort(a + 1, a + 1 + sum1, cmp1);
sort(b + 1, b + 1 + sum2, cmp2);
int flag = n;
long long sum = 0;
for (int i = 1; i <= sum1; i++) {
int nday = a[i].d;
if (amin[a[i].f] == 0) {
amin[a[i].f] = a[i].v;
flag--;
if (flag == 0) {
for (int j = 1; j <= n; j++) {
sum += amin[j];
}
st[nday] = sum;
}
} else if (a[i].v < amin[a[i].f]) {
if (flag == 0) {
sum -= amin[a[i].f] - a[i].v;
amin[a[i].f] = a[i].v;
st[nday] = sum;
} else
amin[a[i].f] = a[i].v;
}
}
if (flag != 0) {
printf("-1\n");
return 0;
}
flag = n;
sum = 0;
for (int i = 1; i <= sum2; i++) {
int nday = b[i].d;
if (bmin[b[i].t] == 0) {
bmin[b[i].t] = b[i].v;
flag--;
if (flag == 0) {
for (int j = 1; j <= n; j++) {
sum += bmin[j];
}
en[nday] = sum;
}
} else if (b[i].v < bmin[b[i].t]) {
if (flag == 0) {
sum -= bmin[b[i].t] - b[i].v;
bmin[b[i].t] = b[i].v;
en[nday] = sum;
} else
bmin[b[i].t] = b[i].v;
}
}
if (flag != 0) {
printf("-1\n");
return 0;
}
for (int i = 1; i <= max1; i++) {
if (st[i] == 0)
st[i] = st[i - 1];
else if (st[i - 1] != 0)
st[i] = min(st[i], st[i - 1]);
}
for (int i = max1; i >= 1; i--) {
if (en[i] == 0)
en[i] = en[i + 1];
else if (en[i + 1] != 0)
en[i] = min(en[i], en[i + 1]);
}
long long min1 = 1e18;
for (int i = 1; i <= max1 - k - 1; i++) {
if (st[i] != 0 && en[i + k + 1] != 0) {
long long dq = st[i] + en[i + k + 1];
min1 = min(min1, dq);
}
}
if (min1 != 1e18)
printf("%I64d\n", min1);
else
printf("-1\n");
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.function.BiFunction;
public class Main{
static Scanner scn = new Scanner(System.in);
static FastScanner sc = new FastScanner();
static Mathplus mp = new Mathplus();
static PrintWriter ot = new PrintWriter(System.out);
static Random rand = new Random();
static int mod = 1000000007;
static long modmod = (long)mod * mod;
static long inf = (long)1e17;
static int[] dx = {0,1,0,-1};
static int[] dy = {1,0,-1,0};
static int[] dx8 = {-1,-1,-1,0,0,1,1,1};
static int[] dy8 = {-1,0,1,-1,1,-1,0,1};
static char[] dc = {'R','D','L','U'};
static BiFunction<Integer,Integer,Integer> fmax = (a,b)-> {return Math.max(a,b);};
static BiFunction<Integer,Integer,Integer> fmin = (a,b)-> {return Math.min(a,b);};
static BiFunction<Integer,Integer,Integer> fsum = (a,b)-> {return a+b;};
static BiFunction<Long,Long,Long> fmaxl = (a,b)-> {return Math.max(a,b);};
static BiFunction<Long,Long,Long> fminl = (a,b)-> {return Math.min(a,b);};
static BiFunction<Long,Long,Long> fsuml = (a,b)-> {return a+b;};
static BiFunction<Integer,Integer,Integer> fadd = fsum;
static BiFunction<Integer,Integer,Integer> fupd = (a,b)-> {return b;};
static BiFunction<Long,Long,Long> faddl = fsuml;
static BiFunction<Long,Long,Long> fupdl = (a,b)-> {return b;};
static String sp = " ";
public static void main(String[] args) {
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int[] d = new int[m];
int[] f = new int[m];
int[] t = new int[m];
long[] c = new long[m];
int D = 1000000;
for(int i=0;i<m;i++) {
d[i] = sc.nextInt()-1;
f[i] = sc.nextInt();
t[i] = sc.nextInt();
c[i] = sc.nextLong();
}
ArrayList<LongIntPair>[] come = new ArrayList[1000000];
ArrayList<LongIntPair>[] back = new ArrayList[1000000];
for(int i=0;i<D;i++) {
come[i] = new ArrayList<LongIntPair>();
back[i] = new ArrayList<LongIntPair>();
}
for(int i=0;i<m;i++) {
if(f[i]==0)back[d[i]].add(new LongIntPair(c[i],t[i]));
if(t[i]==0)come[d[i]].add(new LongIntPair(c[i],f[i]));
}
long[] comecost = new long[D];
long[] eachcome = new long[n+1];
Arrays.fill(eachcome,inf);
int cnt = 0;
long tmp = 0;
for(int i=0;i<D;i++) {
for(LongIntPair p:come[i]) {
if(eachcome[p.b]==inf) {
cnt++;
tmp += p.a;
eachcome[p.b] = p.a;
}else {
if(eachcome[p.b]>p.a) {
tmp -= eachcome[p.b];
tmp += p.a;
eachcome[p.b] = p.a;
}
}
}
comecost[i] = cnt==n?tmp:inf;
}
long[] backcost = new long[D];
long[] eachback = new long[n+1];
Arrays.fill(eachback,inf);
cnt = 0;
tmp = 0;
for(int i=D-1;i>=0;i--) {
for(LongIntPair p:back[i]) {
if(eachback[p.b]==inf) {
cnt++;
tmp += p.a;
eachback[p.b] = p.a;
}else {
if(eachback[p.b]>p.a) {
tmp -= eachback[p.b];
tmp += p.a;
eachback[p.b] = p.a;
}
}
}
backcost[i] = cnt==n?tmp:inf;
}
long min = inf;
for(int i=0;i<D;i++) {
if(i+k+1<D)min = Math.min(min,comecost[i] + backcost[i+k+1]);
}
System.out.println(min==inf?-1:min);
}
}
class Slidemax{
int[] dat;
ArrayDeque<LongIntPair> q = new ArrayDeque<LongIntPair>();
long get() {
if(q.isEmpty()) return (long) -1e17;
return q.peek().a;
}
void remove() {
q.getFirst().b--;
if(q.getFirst().b==0)q.pollFirst();
}
void add(long x) {
int num = 1;
while(!q.isEmpty()&&q.peekLast().a<=x) {
num += q.peekLast().b;
q.pollLast();
}
q.addLast(new LongIntPair(x,num));
}
}
class Slidemin{
int[] dat;
int l = 0;
int r = -1;
ArrayDeque<LongIntPair> q = new ArrayDeque<LongIntPair>();
long get() {
if(q.isEmpty()) return (long)1e17;
return q.peek().a;
}
void remove() {
q.getFirst().b--;
if(q.getFirst().b==0)q.pollFirst();
}
void add(long x) {
int num = 1;
while(!q.isEmpty()&&q.peekLast().a>=x) {
num += q.peekLast().b;
q.pollLast();
}
q.addLast(new LongIntPair(x,num));
}
}
class Counter{
int[] cnt;
Counter(int M){
cnt = new int[M+1];
}
Counter(int M,int[] A){
cnt = new int[M+1];
for(int i=0;i<A.length;i++)add(A[i]);
}
void add(int e) {
cnt[e]++;
}
void remove(int e) {
cnt[e]--;
}
int count(int e) {
return cnt[e];
}
}
class MultiHashSet{
HashMap<Integer,Integer> set;
int size;
long sum;
MultiHashSet(){
set = new HashMap<Integer,Integer>();
size = 0;
sum = 0;
}
void add(int e){
if(set.containsKey(e))set.put(e,set.get(e)+1);
else set.put(e,1);
size++;
sum += e;
}
void remove(int e) {
set.put(e,set.get(e)-1);
if(set.get(e)==0)set.remove(e);
size--;
sum -= e;
}
boolean contains(int e) {
return set.containsKey(e);
}
boolean isEmpty() {
return set.isEmpty();
}
int count(int e) {
if(contains(e))return set.get(e);
else return 0;
}
Set<Integer> keyset(){
return set.keySet();
}
}
class MultiSet{
TreeMap<Integer,Integer> set;
long size;
long sum;
MultiSet(){
set = new TreeMap<Integer,Integer>();
size = 0;
sum = 0;
}
void add(int e){
if(set.containsKey(e))set.put(e,set.get(e)+1);
else set.put(e,1);
size++;
sum += e;
}
void addn(int e,int n){
if(set.containsKey(e))set.put(e,set.get(e)+n);
else set.put(e,n);
size += n;
sum += e*(long)n;
}
void remove(int e) {
set.put(e,set.get(e)-1);
if(set.get(e)==0)set.remove(e);
size--;
sum -= e;
}
int first() {return set.firstKey();}
int last() {return set.lastKey();}
int lower(int e) {return set.lowerKey(e);}
int higher(int e) {return set.higherKey(e);}
int floor(int e) {return set.floorKey(e);}
int ceil(int e) {return set.ceilingKey(e);}
boolean contains(int e) {return set.containsKey(e);}
boolean isEmpty() {return set.isEmpty();}
int count(int e) {
if(contains(e))return set.get(e);
else return 0;
}
MultiSet marge(MultiSet T) {
if(size>T.size) {
while(!T.isEmpty()) {
add(T.first());
T.remove(T.first());
}
return this;
}else {
while(!isEmpty()) {
T.add(first());
remove(first());
}
return T;
}
}
Set<Integer> keyset(){
return set.keySet();
}
}
class MultiSetL{
TreeMap<Long,Integer> set;
int size;
long sum;
MultiSetL(){
set = new TreeMap<Long,Integer>();
size = 0;
sum = 0;
}
void add(long e){
if(set.containsKey(e))set.put(e,set.get(e)+1);
else set.put(e,1);
size++;
sum += e;
}
void remove(long e) {
set.put(e,set.get(e)-1);
if(set.get(e)==0)set.remove(e);
size--;
sum -= e;
}
long first() {return set.firstKey();}
long last() {return set.lastKey();}
long lower(long e) {return set.lowerKey(e);}
long higher(long e) {return set.higherKey(e);}
long floor(long e) {return set.floorKey(e);}
long ceil(long e) {return set.ceilingKey(e);}
boolean contains(long e) {return set.containsKey(e);}
boolean isEmpty() {return set.isEmpty();}
int count(long e) {
if(contains(e))return set.get(e);
else return 0;
}
MultiSetL marge(MultiSetL T) {
if(size>T.size) {
while(!T.isEmpty()) {
add(T.first());
T.remove(T.first());
}
return this;
}else {
while(!isEmpty()) {
T.add(first());
remove(first());
}
return T;
}
}
Set<Long> keyset(){
return set.keySet();
}
}
class BetterGridGraph{
int N;
int M;
char[][] S;
HashMap<Character,ArrayList<Integer>> map;
int[] dx = {0,1,0,-1};
int[] dy = {1,0,-1,0};
char w;
char b = '#';
BetterGridGraph(int n,int m,String[] s,char[] c){
N = n;
M = m;
for(int i=0;i<s.length;i++) {
S[i] = s[i].toCharArray();
}
map = new HashMap<Character,ArrayList<Integer>>();
for(int i=0;i<c.length;i++) {
map.put(c[i],new ArrayList<Integer>());
}
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
for(int k=0;k<c.length;k++) {
if(S[i][j]==c[k])map.get(c[k]).add(toint(i,j));
}
}
}
}
BetterGridGraph(int n,int m,char[][] s,char[] c){
N = n;
M = m;
S = s;
map = new HashMap<Character,ArrayList<Integer>>();
for(int i=0;i<c.length;i++) {
map.put(c[i],new ArrayList<Integer>());
}
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
for(int k=0;k<c.length;k++) {
if(S[i][j]==c[k])map.get(c[k]).add(toint(i,j));
}
}
}
}
BetterGridGraph(int n,int m,String[] s,char[] c,char W,char B){
N = n;
M = m;
for(int i=0;i<s.length;i++) {
S[i] = s[i].toCharArray();
}
w = W;
b = B;
map = new HashMap<Character,ArrayList<Integer>>();
for(int i=0;i<c.length;i++) {
map.put(c[i],new ArrayList<Integer>());
}
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
for(int k=0;k<c.length;k++) {
if(S[i][j]==c[k])map.get(c[k]).add(toint(i,j));
}
}
}
}
BetterGridGraph(int n,int m,char[][] s,char[] c,char W,char B){
N = n;
M = m;
S = s;
w = W;
b = B;
map = new HashMap<Character,ArrayList<Integer>>();
for(int i=0;i<c.length;i++) {
map.put(c[i],new ArrayList<Integer>());
}
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
for(int k=0;k<c.length;k++) {
if(S[i][j]==c[k])map.get(c[k]).add(toint(i,j));
}
}
}
}
int toint(int i,int j) {
return i*M+j;
}
ArrayList<Integer> getposlist(char c) {
return map.get(c);
}
int getpos(char c) {
return map.get(c).get(0);
}
int[] bfs(char C) {
int[] L = new int[N*M];
ArrayDeque<Integer> Q = new ArrayDeque<Integer>();
for(int i=0;i<N*M;i++){
L[i] = -1;
}
for(int s:map.get(C)) {
L[s] = 0;
Q.add(s);
}
Range X = new Range(0,N-1);
Range Y = new Range(0,M-1);
while(!Q.isEmpty()){
int v = Q.poll();
for(int i=0;i<4;i++){
int x = v/M;
int y = v%M;
int nx = x+dx[i];
int ny = y+dy[i];
if(X.isIn(nx)&&Y.isIn(ny)&&S[nx][ny]!=b) {
int w = toint(nx,ny);
if(L[w]==-1){
L[w] = L[v] + 1;
Q.add(w);
}
}
}
}
return L;
}
int[] bfsb(int s) {
int[] L = new int[N*M];
ArrayDeque<Integer> Q = new ArrayDeque<Integer>();
for(int i=0;i<N*M;i++){
L[i] = -1;
}
Q.add(s);
L[s] = 0;
Range X = new Range(0,N-1);
Range Y = new Range(0,M-1);
while(!Q.isEmpty()){
int v = Q.poll();
for(int i=0;i<4;i++){
int x = v/M;
int y = v%M;
int nx = x+dx[i];
int ny = y+dy[i];
if(X.isIn(nx)&&Y.isIn(ny)) {
int w = toint(nx,ny);
if(L[w]==-1){
if(S[x][y]==S[nx][ny]) {
L[w] = L[v];
Q.addFirst(w);
}else {
L[w] = L[v] + 1;
Q.addLast(w);
}
}
}
}
}
return L;
}
int[][] bfs2(char C,int K){
int[][] L = new int[N*M][K+1];
ArrayDeque<IntIntPair> Q = new ArrayDeque<IntIntPair>();
for(int i=0;i<N*M;i++){
for(int j=0;j<=K;j++) {
L[i][j] = 1000000007;
}
}
for(int s:map.get(C)) {
L[s][0] = 0;
Q.add(new IntIntPair(0,s));
}
Range X = new Range(0,N-1);
Range Y = new Range(0,M-1);
while(!Q.isEmpty()){
IntIntPair v = Q.poll();
for(int i=0;i<4;i++){
int x = v.b/M;
int y = v.b%M;
int h = v.a;
int nx = x+dx[i];
int ny = y+dy[i];
if(X.isIn(nx)&&Y.isIn(ny)&&S[nx][ny]!=b) {
int ni = toint(nx,ny);
int nh = S[nx][ny]==w?h+1:h;
if(nh>K) continue;
if(L[ni][nh]==1000000007){
L[ni][nh] = L[v.b][h]+1;
Q.add(new IntIntPair(nh,ni));
}
}
}
}
for(int i=0;i<N*M;i++) {
for(int j=1;j<=K;j++) {
L[i][j] = Math.min(L[i][j],L[i][j-1]);
}
}
return L;
}
}
class IntGridGraph{
int N;
int M;
int[][] B;
int[] dx = {0,1,0,-1};
int[] dy = {1,0,-1,0};
BiFunction<Integer,Integer,Boolean> F;
IntGridGraph(int n,int m,int[][] b){
N = n;
M = m;
B = b;
}
IntGridGraph(int n,int m,int[][] b,BiFunction<Integer,Integer,Boolean> f){
N = n;
M = m;
B = b;
F = f;
}
int toint(int i,int j) {
return i*M+j;
}
int[] bfs(int s) {
int[] L = new int[N*M];
for(int i=0;i<N*M;i++){
L[i] = -1;
}
L[s] = 0;
ArrayDeque<Integer> Q = new ArrayDeque<Integer>();
Q.add(s);
Range X = new Range(0,N-1);
Range Y = new Range(0,M-1);
while(!Q.isEmpty()){
int v = Q.poll();
for(int i=0;i<4;i++){
int x = v/M;
int y = v%M;
int nx = x+dx[i];
int ny = y+dy[i];
if(X.isIn(nx)&&Y.isIn(ny)&&F.apply(B[x][y],B[nx][ny])) {
int w = toint(nx,ny);
if(L[w]==-1){
L[w] = L[v] + 1;
Q.add(w);
}
}
}
}
return L;
}
void bfs(int s,int[] L) {
if(L[s]!=-1) return;
L[s] = 0;
ArrayDeque<Integer> Q = new ArrayDeque<Integer>();
Q.add(s);
Range X = new Range(0,N-1);
Range Y = new Range(0,M-1);
while(!Q.isEmpty()){
int v = Q.poll();
for(int i=0;i<4;i++){
int x = v/M;
int y = v%M;
int nx = x+dx[i];
int ny = y+dy[i];
if(X.isIn(nx)&&Y.isIn(ny)&&F.apply(B[x][y],B[nx][ny])) {
int w = toint(nx,ny);
if(L[w]==-1){
L[w] = L[v] + 1;
Q.add(w);
}
}
}
}
return;
}
int[][] bfs2(int s,int K){
int[][] L = new int[N*M][K+1];
for(int i=0;i<N*M;i++){
for(int j=0;j<=K;j++)
L[i][j] = 1000000007;
}
L[s][0] = 0;
PriorityQueue<IntIntPair> Q = new PriorityQueue<IntIntPair>(new IntIntComparator());
Q.add(new IntIntPair(0,s));
Range X = new Range(0,N-1);
Range Y = new Range(0,M-1);
while(!Q.isEmpty()){
IntIntPair v = Q.poll();
for(int i=0;i<4;i++){
int x = v.b/M;
int y = v.b%M;
int h = v.a;
int nx = x+dx[i];
int ny = y+dy[i];
if(X.isIn(nx)&&Y.isIn(ny)&&F.apply(B[x][y],B[nx][ny])) {
int ni = toint(nx,ny);
int nh = h + B[nx][ny];
if(nh>K) continue;
if(L[ni][nh]==1000000007){
L[ni][nh] = L[v.b][h] + 1;
Q.add(new IntIntPair(nh,ni));
}
}
}
}
for(int i=0;i<N*M;i++) {
for(int j=1;j<=K;j++) {
L[i][j] = Math.min(L[i][j],L[i][j-1]);
}
}
return L;
}
}
class Trie{
int nodenumber = 1;
ArrayList<TrieNode> l;
Trie(){
l = new ArrayList<TrieNode>();
l.add(new TrieNode());
}
void add(String S,int W){
int now = 0;
for(int i=0;i<S.length();i++) {
TrieNode n = l.get(now);
char c = S.charAt(i);
if(n.Exist[c-'a']!=-1) {
now = n.Exist[c-'a'];
}else {
l.add(new TrieNode());
n.Exist[c-'a'] = nodenumber;
now = nodenumber;
nodenumber++;
}
}
l.get(now).weight = W;
}
void find(String S,int i,int[] dp) {
int now = 0;
dp[i+1] = Math.max(dp[i],dp[i+1]);
for(int j=0;;j++) {
TrieNode n = l.get(now);
dp[i+j] = Math.max(dp[i+j],dp[i]+n.weight);
int slook = i+j;
if(slook>=S.length())return;
char c = S.charAt(slook);
if(n.Exist[c-'a']==-1)return;
now = n.Exist[c-'a'];
}
}
}
class TrieNode{
int[] Exist = new int[26];
int weight = 0;
TrieNode(){
for(int i=0;i<26;i++) {
Exist[i] = -1;
}
}
}
class SizeComparator implements Comparator<Edge>{
int[] size;
SizeComparator(int[] s) {
size = s;
}
public int compare(Edge o1, Edge o2) {
return size[o1.to]-size[o2.to];
}
}
class ConvexHullTrick {
long[] A, B;
int len;
public ConvexHullTrick(int n) {
A = new long[n];
B = new long[n];
}
private boolean check(long a, long b) {
return (B[len - 2] - B[len - 1]) * (a - A[len - 1]) >= (B[len - 1] - b) * (A[len - 1] - A[len - 2]);
}
public void add(long a, long b) {
while (len >= 2 && check(a, b)) {
len--;
}
A[len] = a;
B[len] = b;
len++;
}
public long query(long x) {
int l = -1, r = len - 1;
while (r - l > 1) {
int mid = (r + l) / 2;
if (get(mid,x)>=get(mid+1,x)) {
l = mid;
} else {
r = mid;
}
}
return get(r,x);
}
private long get(int k, long x) {
return A[k] * x + B[k];
}
}
class Range{
long l;
long r;
long length;
Range(int L,int R){
l = L;
r = R;
length = R-L+1;
}
public Range(long L, long R) {
l = L;
r = R;
length = R-L+1;
}
boolean isIn(int x) {
return (l<=x&&x<=r);
}
long kasanari(Range S) {
if(this.r<S.l||S.r<this.l) return 0;
else return Math.min(this.r,S.r) - Math.max(this.l,S.l)+1;
}
}
class LeftComparator implements Comparator<Range>{
public int compare(Range P, Range Q) {
return (int) Math.signum(P.l-Q.l);
}
}
class RightComparator implements Comparator<Range>{
public int compare(Range P, Range Q) {
return (int) Math.signum(P.r-Q.r);
}
}
class LengthComparator implements Comparator<Range>{
public int compare(Range P, Range Q) {
return (int) Math.signum(P.length-Q.length);
}
}
class SegmentTree<T,E>{
int N;
BiFunction<T,T,T> f;
BiFunction<T,E,T> g;
T d1;
ArrayList<T> dat;
SegmentTree(BiFunction<T,T,T> F,BiFunction<T,E,T> G,T D1,T[] v){
int n = v.length;
f = F;
g = G;
d1 = D1;
init(n);
build(v);
}
void init(int n) {
N = 1;
while(N<n)N*=2;
dat = new ArrayList<T>();
}
void build(T[] v) {
for(int i=0;i<2*N;i++) {
dat.add(d1);
}
for(int i=0;i<v.length;i++) {
dat.set(N+i-1,v[i]);
}
for(int i=N-2;i>=0;i--) {
dat.set(i,f.apply(dat.get(i*2+1),dat.get(i*2+2)));
}
}
void update(int k,E a) {
k += N-1;
dat.set(k,g.apply(dat.get(k),a));
while(k>0){
k = (k-1)/2;
dat.set(k,f.apply(dat.get(k*2+1),dat.get(k*2+2)));
}
}
T query(int a,int b, int k, int l ,int r) {
if(r<=a||b<=l) return d1;
if(a<=l&&r<=b) return dat.get(k);
T vl = query(a,b,k*2+1,l,(l+r)/2);
T vr = query(a,b,k*2+2,(l+r)/2,r);
return f.apply(vl,vr);
}
T query(int a,int b){
return query(a,b,0,0,N);
}
}
class LazySegmentTree<T,E> extends SegmentTree<T,E>{
BiFunction<E,E,E> h;
BiFunction<E,Integer,E> p = (E a,Integer b) ->{return a;};
E d0;
ArrayList<E> laz;
LazySegmentTree(BiFunction<T,T,T> F,BiFunction<T,E,T> G,BiFunction<E,E,E> H,T D1,E D0,T[] v){
super(F,G,D1,v);
int n = v.length;
h = H;
d0 = D0;
Init(n);
}
void build() {
}
void Init(int n){
laz = new ArrayList<E>();
for(int i=0;i<2*N;i++) {
laz.add(d0);
}
}
void eval(int len,int k) {
if(laz.get(k).equals(d0)) return;
if(k*2+1<N*2-1) {
laz.set(k*2+1,h.apply(laz.get(k*2+1),laz.get(k)));
laz.set(k*2+2,h.apply(laz.get(k*2+2),laz.get(k)));
}
dat.set(k,g.apply(dat.get(k), p.apply(laz.get(k), len)));
laz.set(k,d0);
}
T update(int a,int b,E x,int k,int l,int r) {
eval(r-l,k);
if(r<=a||b<=l) {
return dat.get(k);
}
if(a<=l&&r<=b) {
laz.set(k,h.apply(laz.get(k),x));
return g.apply(dat.get(k),p.apply(laz.get(k),r-l));
}
T vl = update(a,b,x,k*2+1,l,(l+r)/2);
T vr = update(a,b,x,k*2+2,(l+r)/2,r);
dat.set(k,f.apply(vl,vr));
return dat.get(k);
}
T update(int a,int b,E x) {
return update(a,b,x,0,0,N);
}
T query(int a,int b,int k,int l,int r) {
eval(r-l,k);
if(r<=a||b<=l) return d1;
if(a<=l&&r<=b) return dat.get(k);
T vl = query(a,b,k*2+1,l,(l+r)/2);
T vr = query(a,b,k*2+2,(l+r)/2,r);
return f.apply(vl, vr);
}
T query(int a,int b){
return query(a,b,0,0,N);
}
}
class AddSumSegmentTree{
int N;
int d1;
ArrayList<Integer> dat;
AddSumSegmentTree(int[] v){
int n = v.length;
init(n);
build(v);
}
void init(int n) {
N = 1;
while(N<n)N*=2;
dat = new ArrayList<Integer>();
}
void build(int[] v) {
for(int i=0;i<2*N;i++) {
dat.add(d1);
}
for(int i=0;i<v.length;i++) {
dat.set(N+i-1,v[i]);
}
for(int i=N-2;i>=0;i--) {
dat.set(i,dat.get(i*2+1)+dat.get(i*2+2));
}
}
void update(int k,int a) {
k += N-1;
dat.set(k,dat.get(k)+a);
while(k>0){
k = (k-1)/2;
dat.set(k,dat.get(k*2+1)+dat.get(k*2+2));
}
}
int query(int a,int b, int k, int l ,int r) {
if(r<=a||b<=l) return d1;
if(a<=l&&r<=b) return dat.get(k);
int vl = query(a,b,k*2+1,l,(l+r)/2);
int vr = query(a,b,k*2+2,(l+r)/2,r);
return vl+vr;
}
int query(int a,int b){
return query(a,b,0,0,N);
}
}
class AddSumLazySegmentTree {
int N;
long[] dat;
long[] laz;
AddSumLazySegmentTree(long[] v){
init(v.length);
for(int i=0;i<v.length;i++) {
dat[N+i-1]=v[i];
}
for(int i=N-2;i>=0;i--) {
dat[i]=dat[i*2+1]+dat[i*2+2];
}
}
void init(int n) {
N = 1;
while(N<n)N*=2;
dat = new long[2*N];
laz = new long[2*N];
}
void eval(int len,int k) {
if(laz[k]==0) return;
if(k*2+1<N*2-1) {
laz[k*2+1] += laz[k];
laz[k*2+2] += laz[k];
}
dat[k] += laz[k] * len;
laz[k] = 0;
}
long update(int a,int b,long x,int k,int l,int r) {
eval(r-l,k);
if(r<=a||b<=l) {
return dat[k];
}
if(a<=l&&r<=b) {
laz[k] += x;
return dat[k]+laz[k]*(r-l);
}
long vl = update(a,b,x,k*2+1,l,(l+r)/2);
long vr = update(a,b,x,k*2+2,(l+r)/2,r);
return dat[k] = vl+vr;
}
long update(int a,int b,long x) {
return update(a,b,x,0,0,N);
}
long query(int a,int b,int k,int l,int r) {
eval(r-l,k);
if(r<=a||b<=l) return 0;
if(a<=l&&r<=b) return dat[k];
long vl = query(a,b,k*2+1,l,(l+r)/2);
long vr = query(a,b,k*2+2,(l+r)/2,r);
return vl+vr;
}
long query(int a,int b){
return query(a,b,0,0,N);
}
}
class BinaryIndexedTree{
int[] val;
BinaryIndexedTree(int N){
val = new int[N+1];
}
long sum(int i) {
if(i==0)return 0;
long s = 0;
while(i>0) {
s += val[i];
i -= i & (-i);
}
return s;
}
void add(int i,int x) {
if(i==0)return;
while(i<val.length){
val[i] += x;
i += i & (-i);
}
}
}
class UnionFindTree {
int[] root;
int[] rank;
long[] size;
int[] edge;
int num;
UnionFindTree(int N){
root = new int[N];
rank = new int[N];
size = new long[N];
edge = new int[N];
num = N;
for(int i=0;i<N;i++){
root[i] = i;
size[i] = 1;
}
}
public long size(int x) {
return size[find(x)];
}
public boolean isRoot(int x) {
return x==find(x);
}
public long extraEdge(int x) {
int r = find(x);
return edge[r] - size[r] + 1;
}
public int find(int x){
if(root[x]==x){
return x;
}else{
return find(root[x]);
}
}
public boolean unite(int x,int y){
x = find(x);
y = find(y);
if(x==y){
edge[x]++;
return false;
}else{
num--;
if(rank[x]<rank[y]){
root[x] = y;
size[y] += size[x];
edge[y] += edge[x]+1;
}else{
root[y] = x;
size[x] += size[y];
edge[x] += edge[y]+1;
if(rank[x]==rank[y]){
rank[x]++;
}
}
return true;
}
}
public boolean same(int x,int y){
return find(x)==find(y);
}
}
class LightUnionFindTree {
int[] par;
int num;
LightUnionFindTree(int N){
par = new int[N];
num = N;
for(int i=0;i<N;i++){
par[i] = -1;
}
}
public boolean isRoot(int x) {
return x==find(x);
}
public int find(int x){
if(par[x]<0){
return x;
}else{
return find(par[x]);
}
}
public void unite(int x,int y){
x = find(x);
y = find(y);
if(x==y){
return;
}else{
num--;
if(par[x]<par[y]){
par[x] += par[y];
par[y] = x;
}else{
par[y] += par[x];
par[x] = y;
}
}
}
public boolean same(int x,int y){
return find(x)==find(y);
}
}
class ParticalEternalLastingUnionFindTree extends UnionFindTree{
int[] time;
int now;
ParticalEternalLastingUnionFindTree(int N){
super(N);
time = new int[N];
for(int i=0;i<N;i++) {
time[i] = 1000000007;
}
}
public int find(int t,int i) {
if(time[i]>t) {
return i;
}else {
return find(t,root[i]);
}
}
public void unite(int x,int y,int t) {
now = t;
x = find(t,x);
y = find(t,y);
if(x==y)return;
if(rank[x]<rank[y]){
root[x] = y;
size[y] += size[x];
time[x] = t;
}else{
root[y] = x;
size[x] += size[y];
if(rank[x]==rank[y]){
rank[x]++;
}
time[y] = t;
}
}
public int sametime(int x,int y) {
if(find(now,x)!=find(now,y)) return -1;
int ok = now;
int ng = 0;
while(ok-ng>1) {
int mid = (ok+ng)/2;
if(find(mid,x)==find(mid,y)) {
ok = mid;
}else {
ng = mid;
}
}
return ok;
}
}
class FlowEdge{
int to;
long cap;
int rev = 0;
FlowEdge(int To,long Cap,int Rev){
to = To;
cap = Cap;
rev = Rev;
}
}
class FlowGraph{
ArrayList<FlowEdge>[] list;
int[] level;
int[] iter;
ArrayDeque<Integer> q;
FlowGraph(int N){
list = new ArrayList[N];
for(int i=0;i<N;i++) {
list[i] = new ArrayList<FlowEdge>();
}
level = new int[N];
iter = new int[N];
q = new ArrayDeque<Integer>();
}
void addEdge(int i, int to, long cap) {
list[i].add(new FlowEdge(to,cap,list[to].size()));
list[to].add(new FlowEdge(i,0,list[i].size()-1));
}
void bfs(int s) {
Arrays.fill(level,-1);
level[s] = 0;
q.add(s);
while(!q.isEmpty()) {
int v = q.poll();
for(FlowEdge e:list[v]) {
if(e.cap>0&&level[e.to]<0) {
level[e.to] = level[v] + 1;
q.add(e.to);
}
}
}
}
long dfs(int v,int t,long f) {
if(v==t) return f;
for(int i = iter[v];i<list[v].size();i++) {
FlowEdge e = list[v].get(i);
if(e.cap>0&&level[v]<level[e.to]) {
long d = dfs(e.to,t,Math.min(f,e.cap));
if(d>0) {
e.cap -= d;
list[e.to].get(e.rev).cap += d;
return d;
}
}
iter[v]++;
}
return 0;
}
long flow(int s,int t,long lim) {
long flow = 0;
while(true) {
bfs(s);
if(level[t]<0||lim==0) return flow;
Arrays.fill(iter,0);
while(true) {
long f = dfs(s,t,lim);
if(f>0) {
flow += f;
lim -= f;
}
else break;
}
}
}
long flow(int s,int t) {
return flow(s,t,1000000007);
}
}
class Graph {
ArrayList<Edge>[] list;
int size;
TreeSet<LinkEdge> Edges = new TreeSet<LinkEdge>(new LinkEdgeComparator());
@SuppressWarnings("unchecked")
Graph(int N){
size = N;
list = new ArrayList[N];
for(int i=0;i<N;i++){
list[i] = new ArrayList<Edge>();
}
}
public long[] dicount(int s) {
long[] L = new long[size];
long[] c = new long[size];
int mod = 1000000007;
for(int i=0;i<size;i++){
L[i] = -1;
}
int[] v = new int[size];
L[s] = 0;
c[s] = 1;
PriorityQueue<LongIntPair> Q = new PriorityQueue<LongIntPair>(new LongIntComparator());
Q.add(new LongIntPair(0,s));
while(!Q.isEmpty()){
LongIntPair C = Q.poll();
if(v[C.b]==0){
L[C.b] = C.a;
v[C.b] = 1;
for(Edge D:list[C.b]) {
//System.out.println(C.b +" "+ D.to);
if(L[D.to]==-1||L[D.to]>L[C.b]+D.cost) {
L[D.to]=L[C.b]+D.cost;
c[D.to] = c[C.b];
Q.add(new LongIntPair(L[C.b]+D.cost,D.to));
}else if(L[D.to]==L[C.b]+D.cost) {
c[D.to] += c[C.b];
}
c[D.to] %= mod;
}
}
}
return c;
}
public long[] roots(int s) {
int[] in = new int[size];
ArrayDeque<Integer> q = new ArrayDeque<Integer>();
long[] N = new long[size];
long mod = 1000000007;
for(int i=0;i<size;i++) {
for(Edge e:list[i])in[e.to]++;
}
for(int i=0;i<size;i++) {
if(in[i]==0)q.add(i);
}
N[s] = 1;
while(!q.isEmpty()) {
int v = q.poll();
for(Edge e:list[v]) {
N[e.to] += N[v];
if(N[e.to]>=mod)N[e.to]-= mod;
in[e.to]--;
if(in[e.to]==0)q.add(e.to);
}
}
return N;
}
void addEdge(int a,int b){
list[a].add(new Edge(b,1));
}
void addWeightedEdge(int a,int b,long c){
list[a].add(new Edge(b,c));
}
void addEgdes(int[] a,int[] b){
for(int i=0;i<a.length;i++){
list[a[i]].add(new Edge(b[i],1));
}
}
void addWeightedEdges(int[] a ,int[] b ,int[] c){
for(int i=0;i<a.length;i++){
list[a[i]].add(new Edge(b[i],c[i]));
}
}
long[] bfs(int s){
long[] L = new long[size];
for(int i=0;i<size;i++){
L[i] = -1;
}
L[s] = 0;
ArrayDeque<Integer> Q = new ArrayDeque<Integer>();
Q.add(s);
while(!Q.isEmpty()){
int v = Q.poll();
for(Edge e:list[v]){
int w = e.to;
long c = e.cost;
if(L[w]==-1){
L[w] = L[v] + c;
Q.add(w);
}
}
}
return L;
}
long[][] bfswithrev(int s){
long[][] L = new long[2][size];
for(int i=0;i<size;i++){
L[0][i] = -1;
L[1][i] = -1;
}
L[0][s] = 0;
ArrayDeque<Integer> Q = new ArrayDeque<Integer>();
Q.add(s);
while(!Q.isEmpty()){
int v = Q.poll();
for(Edge e:list[v]){
int w = e.to;
long c = e.cost;
if(L[0][w]==-1){
L[0][w] = L[0][v] + c;
L[1][w] = v;
Q.add(w);
}
}
}
return L;
}
long[] bfs2(int[] d,int s){
long[] L = new long[size];
for(int i=0;i<size;i++){
L[i] = -1;
}
int p = 0;
L[s] = 0;
d[s] = p;
p++;
ArrayDeque<Integer> Q = new ArrayDeque<Integer>();
Q.add(s);
while(!Q.isEmpty()){
int v = Q.poll();
for(Edge e:list[v]){
int w = e.to;
long c = e.cost;
if(L[w]==-1){
d[w] = p;
p++;
L[w] = L[v] + c;
Q.add(w);
}
}
}
return L;
}
boolean bfs3(int s,long[] L, int[] vi){
if(vi[s]==1) return true;
vi[s] = 1;
ArrayDeque<Integer> Q = new ArrayDeque<Integer>();
Q.add(s);
while(!Q.isEmpty()){
int v = Q.poll();
for(Edge e:list[v]){
int w = e.to;
long c = e.cost;
if(vi[e.to]==0) {
L[e.to] = (int)c - L[v];
Q.add(w);
vi[e.to] = 1;
}else {
if(L[e.to]!=(int)c - L[v]) {
return false;
}
}
}
}
return true;
}
int[] isTwoColor(){
int[] L = new int[size];
for(int i=0;i<size;i++){
L[i] = -1;
}
L[0] = 0;
ArrayDeque<Integer> Q = new ArrayDeque<Integer>();
Q.add(0);
while(!Q.isEmpty()){
int v = Q.poll();
for(Edge e:list[v]){
int w = e.to;
if(L[w]==-1){
L[w] = 1-L[v];
Q.add(w);
}else{
if(L[v]+L[w]!=1){
L[0] = -2;
}
}
}
}
return L;
}
void isTwoColor2(int i,int[] L){
L[i] = 0;
ArrayDeque<Integer> Q = new ArrayDeque<Integer>();
Q.add(i);
while(!Q.isEmpty()){
int v = Q.poll();
for(Edge e:list[v]){
int w = e.to;
if(L[w]==-1){
L[w] = 1-L[v];
Q.add(w);
}else{
if(L[v]+L[w]!=1){
L[0] = -2;
}
}
}
}
}
long[] dijkstra(int s){
long[] L = new long[size];
for(int i=0;i<size;i++){
L[i] = -1;
}
int[] v = new int[size];
L[s] = 0;
PriorityQueue<LongIntPair> Q = new PriorityQueue<LongIntPair>(new LongIntComparator());
Q.add(new LongIntPair(0,s));
while(!Q.isEmpty()){
LongIntPair C = Q.poll();
if(v[C.b]==0){
L[C.b] = C.a;
v[C.b] = 1;
for(Edge D:list[C.b]) {
if(L[D.to]==-1||L[D.to]>L[C.b]+D.cost) {
L[D.to]=L[C.b]+D.cost;
Q.add(new LongIntPair(L[C.b]+D.cost,D.to));
}
}
}
}
return L;
}
ArrayList<Graph> makeapart(){
ArrayList<Graph> ans = new ArrayList<Graph>();
boolean[] b = new boolean[size];
int[] num = new int[size];
for(int i=0;i<size;i++){
if(b[i])continue;
int sz = 0;
ArrayList<Integer> l = new ArrayList<Integer>();
ArrayDeque<Integer> Q = new ArrayDeque<Integer>();
Q.add(i);
b[i] = true;
while(!Q.isEmpty()){
int v = Q.poll();
num[v] = sz;
sz++;
l.add(v);
for(Edge e:list[v]){
if(!b[e.to]){
Q.add(e.to);
b[e.to] = true;
}
}
}
Graph H = new Graph(sz);
for(int e:l){
for(Edge E:list[e]){
H.addWeightedEdge(num[e],num[E.to],E.cost);
}
}
ans.add(H);
}
return ans;
}
long[] bellmanFord(int s) {
long inf = 1000000000;
inf *= inf;
long[] d = new long[size];
boolean[] n = new boolean[size];
d[s] = 0;
for(int i=1;i<size;i++){
d[i] = inf;
d[i] *= d[i];
}
for(int i=0;i<size-1;i++){
for(int j=0;j<size;j++){
for(Edge E:list[j]){
if(d[j]!=inf&&d[E.to]>d[j]+E.cost){
d[E.to]=d[j]+E.cost;
}
}
}
}
for(int i=0;i<size;i++){
for(int j=0;j<size;j++){
for(Edge e:list[j]){
if(d[j]==inf) continue;
if(d[e.to]>d[j]+e.cost) {
d[e.to]=d[j]+e.cost;
n[e.to] = true;
}
if(n[j])n[e.to] = true;
}
}
}
for(int i=0;i<size;i++) {
if(n[i])d[i] = inf;
}
return d;
}
long[][] WarshallFloyd(long[][] a){
int n = a.length;
long[][] ans = new long[n][n];
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
ans[i][j] = a[i][j]==0?(long)1e16:a[i][j];
if(i==j)ans[i][j]=0;
}
}
for(int k=0;k<n;k++) {
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
ans[i][j] = Math.min(ans[i][j],ans[i][k]+ans[k][j]);
}
}
}
return ans;
}
long[] maxtra(int s,long l){
long[] L = new long[size];
for(int i=0;i<size;i++){
L[i] = -1;
}
int[] v = new int[size];
L[s] = -1;
PriorityQueue<Pair> Q = new PriorityQueue<Pair>(new SampleComparator());
Q.add(new Pair(l,s));
while(!Q.isEmpty()){
Pair C = Q.poll();
if(v[(int)C.b]==0){
L[(int)C.b] = C.a;
v[(int) C.b] = 1;
for(Edge D:list[(int) C.b])Q.add(new Pair(Math.max(L[(int)C.b],D.cost),D.to));
}
}
return L;
}
long[] mintra(int s){
long[] L = new long[size];
for(int i=0;i<size;i++){
L[i] = -1;
}
int[] v = new int[size];
L[s] = s;
PriorityQueue<Pair> Q = new PriorityQueue<Pair>(new SampleComparator().reversed());
Q.add(new Pair(s,s));
while(!Q.isEmpty()){
Pair C = Q.poll();
if(v[(int)C.b]==0){
L[(int)C.b] = C.a;
v[(int) C.b] = 1;
for(Edge D:list[(int) C.b])Q.add(new Pair(Math.min(L[(int)C.b],D.cost),D.to));
}
}
return L;
}
long Kruskal(){
long r = 0;
for(int i=0;i<size;i++) {
for(Edge e:list[i]) {
Edges.add(new LinkEdge(e.cost,i,e.to));
}
}
UnionFindTree UF = new UnionFindTree(size);
for(LinkEdge e:Edges){
if(e.a>=0&&e.b>=0) {
if(!UF.same(e.a,e.b)){
r += e.L;
UF.unite(e.a,e.b);
}
}
}
return r;
}
ArrayList<Integer> Kahntsort(){
ArrayList<Integer> ans = new ArrayList<Integer>();
PriorityQueue<Integer> q = new PriorityQueue<Integer>();
int[] in = new int[size];
for(int i=0;i<size;i++) {
for(Edge e:list[i])in[e.to]++;
}
for(int i=0;i<size;i++) {
if(in[i]==0)q.add(i);
}
while(!q.isEmpty()) {
int v = q.poll();
ans.add(v);
for(Edge e:list[v]) {
in[e.to]--;
if(in[e.to]==0)q.add(e.to);
}
}
for(int i=0;i<size;i++) {
if(in[i]>0)return new ArrayList<Integer>();
}
return ans;
}
public Stack<Integer> findCycle() {
Stack<Integer> ans = new Stack<Integer>();
boolean[] v = new boolean[size];
boolean[] f = new boolean[size];
for(int i=0;i<size;i++) {
if(findCycle(i,ans,v,f))break;
}
return ans;
}
private boolean findCycle(int i, Stack<Integer>ans, boolean[] v,boolean[] f) {
v[i] = true;
ans.push(i);
for(Edge e:list[i]) {
if(f[e.to]) continue;
if(v[e.to]&&!f[e.to]) {
return true;
}
if(findCycle(e.to,ans,v,f))return true;
}
ans.pop();
f[i] = true;
return false;
}
RootedTree dfsTree(int i) {
int[] u = new int[size];
RootedTree r = new RootedTree(size);
dfsTree(i,u,r);
return r;
}
private void dfsTree(int i, int[] u, RootedTree r) {
u[i] = 1;
r.trans[r.node] = i;
r.rev[i] = r.node;
r.node++;
for(Edge e:list[i]) {
if(u[e.to]==0) {
r.list[i].add(e);
u[e.to] = 1;
dfsTree(e.to,u,r);
}
}
}
}
class LightGraph {
ArrayList<Integer>[] list;
int size;
TreeSet<LinkEdge> Edges = new TreeSet<LinkEdge>(new LinkEdgeComparator());
@SuppressWarnings("unchecked")
LightGraph(int N){
size = N;
list = new ArrayList[N];
for(int i=0;i<N;i++){
list[i] = new ArrayList<Integer>();
}
}
void addEdge(int a,int b){
list[a].add(b);
}
public Stack<Integer> findCycle() {
Stack<Integer> ans = new Stack<Integer>();
boolean[] v = new boolean[size];
boolean[] f = new boolean[size];
for(int i=0;i<size;i++) {
if(findCycle(i,ans,v,f))break;
}
return ans;
}
private boolean findCycle(int i, Stack<Integer>ans, boolean[] v,boolean[] f) {
v[i] = true;
ans.push(i);
for(int e:list[i]) {
if(f[e]) continue;
if(v[e]&&!f[e]) {
return true;
}
if(findCycle(e,ans,v,f))return true;
}
ans.pop();
f[i] = true;
return false;
}
}
class Tree extends Graph{
public Tree(int N) {
super(N);
}
long[] tyokkei(){
long[] a = bfs(0);
int md = -1;
long m = 0;
for(int i=0;i<size;i++){
if(m<a[i]){
m = a[i];
md = i;
}
}
long[] b = bfs(md);
int md2 = -1;
long m2 = 0;
for(int i=0;i<size;i++){
if(m2<b[i]){
m2 = b[i];
md2 = i;
}
}
long[] r = {m2,md,md2};
return r;
}
int[] size(int r) {
int[] ret = new int[size];
dfssize(r,-1,ret);
return ret;
}
private int dfssize(int i, int rev, int[] ret) {
int sz = 1;
for(Edge e:list[i]) {
if(e.to!=rev) sz += dfssize(e.to,i,ret);
}
return ret[i] = sz;
}
}
class RootedTree extends Graph{
int[] trans;
int[] rev;
int node = 0;
RootedTree(int N){
super(N);
trans = new int[N];
rev = new int[N];
}
public int[] parents() {
int[] ret = new int[size];
for(int i=0;i<size;i++) {
for(Edge e:list[i]) {
ret[rev[e.to]] = rev[i];
}
}
ret[0] = -1;
return ret;
}
}
class LinkEdge{
long L;
int a ;
int b;
int id;
LinkEdge(long l,int A,int B){
L = l;
a = A;
b = B;
}
LinkEdge(long l,int A,int B,int i){
L = l;
a = A;
b = B;
id = i;
}
public boolean equals(Object o){
LinkEdge O = (LinkEdge) o;
return O.a==this.a&&O.b==this.b&&O.L==this.L;
}
public int hashCode(){
return Objects.hash(L,a,b);
}
}
class DoubleLinkEdge{
double D;
int a;
int b;
DoubleLinkEdge(double d,int A,int B){
D = d;
a = A;
b = B;
}
public boolean equals(Object o){
DoubleLinkEdge O = (DoubleLinkEdge) o;
return O.a==this.a&&O.b==this.b&&O.D==this.D;
}
public int hashCode(){
return Objects.hash(D,a,b);
}
}
class Edge{
int to;
long cost;
Edge(int a,long b){
to = a;
cost = b;
}
}
class indexedEdge extends Edge{
int id;
indexedEdge(int a, long b, int c) {
super(a,b);
id = c;
}
}
class DoubleLinkEdgeComparator implements Comparator<DoubleLinkEdge>{
public int compare(DoubleLinkEdge P, DoubleLinkEdge Q) {
return Double.compare(P.D,Q.D);
}
}
class LinkEdgeComparator implements Comparator<LinkEdge>{
public int compare(LinkEdge P, LinkEdge Q) {
return Long.compare(P.L,Q.L);
}
}
class Pair{
long a;
long b;
Pair(long p,long q){
this.a = p;
this.b = q;
}
public boolean equals(Object o){
Pair O = (Pair) o;
return O.a==this.a&&O.b==this.b;
}
public int hashCode(){
return Objects.hash(a,b);
}
}
class SampleComparator implements Comparator<Pair>{
public int compare(Pair P, Pair Q) {
long t = P.a-Q.a;
if(t==0){
if(P.b==Q.b)return 0;
return P.b>Q.b?1:-1;
}
return t>=0?1:-1;
}
}
class LongIntPair{
long a;
int b;
LongIntPair(long p,int q){
this.a = p;
this.b = q;
}
public boolean equals(Object o){
LongIntPair O = (LongIntPair) o;
return O.a==this.a&&O.b==this.b;
}
public int hashCode(){
return Objects.hash(a,b);
}
}
class LongIntComparator implements Comparator<LongIntPair>{
public int compare(LongIntPair P, LongIntPair Q) {
long t = P.a-Q.a;
if(t==0){
if(P.b>Q.b){
return 1;
}else{
return -1;
}
}
return t>=0?1:-1;
}
}
class IntIntPair{
int a;
int b;
IntIntPair(int p,int q){
this.a = p;
this.b = q;
}
IntIntPair(int p,int q,String s){
if(s.equals("sort")) {
this.a = Math.min(p,q);
this.b = Math.max(p,q);
}
}
public boolean equals(Object o){
IntIntPair O = (IntIntPair) o;
return O.a==this.a&&O.b==this.b;
}
public int hashCode(){
return Objects.hash(a,b);
}
}
class IntIntComparator implements Comparator<IntIntPair>{
public int compare(IntIntPair P, IntIntPair Q) {
int t = P.a-Q.a;
if(t==0){
return P.b-Q.b;
}
return t;
}
}
class CIPair{
char c;
int i;
CIPair(char C,int I){
c = C;
i = I;
}
public boolean equals(Object o){
CIPair O = (CIPair) o;
return O.c==this.c&&O.i==this.i;
}
public int hashCode(){
return Objects.hash(c,i);
}
}
class DoublePair{
double a;
double b;
DoublePair(double p,double q){
this.a = p;
this.b = q;
}
public boolean equals(Object o){
DoublePair O = (DoublePair) o;
return O.a==this.a&&O.b==this.b;
}
public int hashCode(){
return Objects.hash(a,b);
}
}
class Triplet{
long a;
long b;
long c;
Triplet(long p,long q,long r){
a = p;
b = q;
c = r;
}
public boolean equals(Object o){
Triplet O = (Triplet) o;
return O.a==this.a&&O.b==this.b&&O.c==this.c?true:false;
}
public int hashCode(){
return Objects.hash(a,b,c);
}
}
class TripletComparator implements Comparator<Triplet>{
public int compare(Triplet P, Triplet Q) {
long t = P.a-Q.a;
if(t==0){
long tt = P.b-Q.b;
if(tt==0) {
if(P.c>Q.c) {
return 1;
}else if(P.c<Q.c){
return -1;
}else {
return 0;
}
}
return tt>0?1:-1;
}
return t>=0?1:-1;
}
}
class DDComparator implements Comparator<DoublePair>{
public int compare(DoublePair P, DoublePair Q) {
return P.a-Q.a>=0?1:-1;
}
}
class DoubleTriplet{
double a;
double b;
double c;
DoubleTriplet(double p,double q,double r){
this.a = p;
this.b = q;
this.c = r;
}
public boolean equals(Object o){
DoubleTriplet O = (DoubleTriplet) o;
return O.a==this.a&&O.b==this.b&&O.c==this.c;
}
public int hashCode(){
return Objects.hash(a,b,c);
}
}
class DoubleTripletComparator implements Comparator<DoubleTriplet>{
public int compare(DoubleTriplet P, DoubleTriplet Q) {
if(P.a==Q.a) return 0;
return P.a-Q.a>0?1:-1;
}
}
class FastScanner {
private final java.io.InputStream in = System.in;
private final byte[] b = new byte[1024];
private int p = 0;
private int bl = 0;
private boolean hNB() {
if (p<bl) {
return true;
}else{
p = 0;
try {
bl = in.read(b);
} catch (IOException e) {
e.printStackTrace();
}
if (bl<=0) {
return false;
}
}
return true;
}
private int rB() { if (hNB()) return b[p++]; else return -1;}
private static boolean iPC(int c) { return 33 <= c && c <= 126;}
private void sU() { while(hNB() && !iPC(b[p])) p++;}
public boolean hN() { sU(); return hNB();}
public String next() {
if (!hN()) throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = rB();
while(iPC(b)) {
sb.appendCodePoint(b);
b = rB();
}
return sb.toString();
}
public char nextChar() {
return next().charAt(0);
}
public long nextLong() {
if (!hN()) throw new NoSuchElementException();
long n = 0;
boolean m = false;
int b = rB();
if (b=='-') {
m=true;
b=rB();
}
if (b<'0'||'9'<b) {
throw new NumberFormatException();
}
while(true){
if ('0'<=b&&b<='9') {
n *= 10;
n += b - '0';
}else if(b == -1||!iPC(b)){
return (m?-n:n);
}else{
throw new NumberFormatException();
}
b = rB();
}
}
public int nextInt() {
if (!hN()) throw new NoSuchElementException();
long n = 0;
boolean m = false;
int b = rB();
if (b == '-') {
m = true;
b = rB();
}
if (b<'0'||'9'<b) {
throw new NumberFormatException();
}
while(true){
if ('0'<=b&&b<='9') {
n *= 10;
n += b-'0';
}else if(b==-1||!iPC(b)){
return (int) (m?-n:n);
}else{
throw new NumberFormatException();
}
b = rB();
}
}
public int[] nextInts(int n) {
int[] a = new int[n];
for(int i=0;i<n;i++) {
a[i] = nextInt();
}
return a;
}
public int[] nextInts(int n,int s) {
int[] a = new int[n+s];
for(int i=s;i<n+s;i++) {
a[i] = nextInt();
}
return a;
}
public long[] nextLongs(int n, int s) {
long[] a = new long[n+s];
for(int i=s;i<n+s;i++) {
a[i] = nextLong();
}
return a;
}
public long[] nextLongs(int n) {
long[] a = new long[n];
for(int i=0;i<n;i++) {
a[i] = nextLong();
}
return a;
}
public int[][] nextIntses(int n,int m){
int[][] a = new int[n][m];
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
a[i][j] = nextInt();
}
}
return a;
}
public String[] nexts(int n) {
String[] a = new String[n];
for(int i=0;i<n;i++) {
a[i] = next();
}
return a;
}
void nextIntses(int n,int[] ...m) {
int l = m[0].length;
for(int i=0;i<l;i++) {
for(int j=0;j<m.length;j++) {
m[j][i] = nextInt();
}
}
}
void nextLongses(int n,long[] ...m) {
int l = m[0].length;
for(int i=0;i<l;i++) {
for(int j=0;j<m.length;j++) {
m[j][i] = nextLong();
}
}
}
Graph nextyukoGraph(int n,int m) {
Graph G = new Graph(n);
for(int i=0;i<m;i++) {
int a = nextInt()-1;
int b = nextInt()-1;
G.addEdge(a,b);
}
return G;
}
Graph nextGraph(int n,int m) {
Graph G = new Graph(n);
for(int i=0;i<m;i++) {
int a = nextInt()-1;
int b = nextInt()-1;
G.addEdge(a,b);
G.addEdge(b,a);
}
return G;
}
Graph nextWeightedGraph(int n,int m) {
Graph G = new Graph(n);
for(int i=0;i<m;i++) {
int a = nextInt()-1;
int b = nextInt()-1;
long c = nextLong();
G.addWeightedEdge(a,b,c);
G.addWeightedEdge(b,a,c);
}
return G;
}
Tree nextTree(int n) {
Tree T = new Tree(n);
for(int i=0;i<n-1;i++) {
int a = nextInt()-1;
int b = nextInt()-1;
T.addEdge(a,b);
T.addEdge(b,a);
}
return T;
}
}
class Mathplus{
long mod = 1000000007;
long[] fac;
long[] revfac;
long[][] comb;
long[] pow;
long[] revpow;
boolean isBuild = false;
boolean isBuildc = false;
boolean isBuildp = false;
int mindex = -1;
int maxdex = -1;
int graydiff = 0;
int graymark = 0;
int LIS(int N, int[] a) {
int[] dp = new int[N+1];
Arrays.fill(dp,(int)mod);
for(int i=0;i<N;i++) {
int ok = 0;
int ng = N;
while(ng-ok>1) {
int mid = (ok+ng)/2;
if(dp[mid]<a[i])ok = mid;
else ng = mid;
}
dp[ok+1] = a[i];
}
int ok = 0;
for(int i=1;i<=N;i++) {
if(dp[i]<mod)ok=i;
}
return ok;
}
public Integer[] Ints(int n, int i) {
Integer[] ret = new Integer[n];
Arrays.fill(ret,i);
return ret;
}
public Long[] Longs(int n, long i) {
Long[] ret = new Long[n];
Arrays.fill(ret,i);
return ret;
}
public boolean nexperm(int[] p) {
int n = p.length;
for(int i=n-1;i>0;i--) {
if(p[i-1]<p[i]) {
int sw = n;
for(int j=n-1;j>=i;j--) {
if(p[i-1]<p[j]) {
sw = j;
break;
}
}
int tmp = p[i-1];
p[i-1] = p[sw];
p[sw] = tmp;
int[] r = new int[n];
for(int j=i;j<n;j++) {
r[j] = p[n-1-j+i];
}
for(int j=i;j<n;j++) {
p[j] = r[j];
}
return true;
}
}
return false;
}
public int[] makeperm(int n) {
int[] a = new int[n];
for(int i=0;i<n;i++) {
a[i] = i;
}
return a;
}
public void timeout() throws InterruptedException {
Thread.sleep(10000);
}
public int gray(int i) {
for(int j=0;j<20;j++) {
if(contains(i,j)) {
graydiff = j;
if(contains(i,j+1))graymark=-1;
else graymark = 1;
break;
}
}
return i ^ (i>>1);
}
public void printjudge(boolean b, String y, String n) {
System.out.println(b?y:n);
}
public void printYN(boolean b) {
printjudge(b,"Yes","No");
}
public void printyn(boolean b) {
printjudge(b,"yes","no");
}
public void reverse(int[] x) {
int[] r = new int[x.length];
for(int i=0;i<x.length;i++)r[i] = x[x.length-1-i];
for(int i=0;i<x.length;i++)x[i] = r[i];
}
public void reverse(long[] x) {
long[] r = new long[x.length];
for(int i=0;i<x.length;i++)r[i] = x[x.length-1-i];
for(int i=0;i<x.length;i++)x[i] = r[i];
}
public DoubleTriplet Line(double x1,double y1,double x2,double y2) {
double a = y1-y2;
double b = x2-x1;
double c = x1*y2-x2*y1;
return new DoubleTriplet(a,b,c);
}
public double putx(DoubleTriplet T,double x) {
return -(T.a*x+T.c)/T.b;
}
public double puty(DoubleTriplet T,double y) {
return -(T.b*y+T.c)/T.a;
}
public double Distance(DoublePair P,DoublePair Q) {
return Math.sqrt((P.a-Q.a) * (P.a-Q.a) + (P.b-Q.b) * (P.b-Q.b));
}
public double DistanceofPointandLine(DoublePair P,Triplet T) {
return Math.abs(P.a*T.a+P.b*T.b+T.c) / Math.sqrt(T.a*T.a+T.b*T.b);
}
public boolean cross(long ax, long ay, long bx, long by, long cx, long cy, long dx, long dy) {
if((ax-bx)*(cy-dy)==(ay-by)*(cx-dx)) {
if(ax-bx!=0) {
Range A = new Range(ax,bx);
Range B = new Range(cx,dx);
return A.kasanari(B)>0;
}else {
Range A = new Range(ay,by);
Range B = new Range(cy,dy);
return A.kasanari(B)>0;
}
}
long ta = (cx - dx) * (ay - cy) + (cy - dy) * (cx - ax);
long tb = (cx - dx) * (by - cy) + (cy - dy) * (cx - bx);
long tc = (ax - bx) * (cy - ay) + (ay - by) * (ax - cx);
long td = (ax - bx) * (dy - ay) + (ay - by) * (ax - dx);
return((tc>=0&&td<=0)||(tc<=0&&td>=0))&&((ta>=0&&tb<=0)||(ta<=0&&tb>=0));
}
public boolean dcross(double ax, double ay, double bx, double by, double cx, double cy, double dx, double dy) {
double ta = (cx - dx) * (ay - cy) + (cy - dy) * (cx - ax);
double tb = (cx - dx) * (by - cy) + (cy - dy) * (cx - bx);
double tc = (ax - bx) * (cy - ay) + (ay - by) * (ax - cx);
double td = (ax - bx) * (dy - ay) + (ay - by) * (ax - dx);
return((tc>=0&&td<=0)||(tc<=0&&td>=0))&&((ta>=0&&tb<=0)||(ta<=0&&tb>=0));
}
void buildFac(){
fac = new long[10000003];
revfac = new long[10000003];
fac[0] = 1;
for(int i=1;i<=10000002;i++){
fac[i] = (fac[i-1] * i)%mod;
}
revfac[10000002] = rev(fac[10000002])%mod;
for(int i=10000001;i>=0;i--) {
revfac[i] = (revfac[i+1] * (i+1))%mod;
}
isBuild = true;
}
void buildFacn(int n){
fac = new long[n+1];
revfac = new long[n+1];
fac[0] = 1;
for(int i=1;i<=n;i++){
fac[i] = (fac[i-1] * i)%mod;
}
revfac[n] = rev(fac[n])%mod;
for(int i=n-1;i>=0;i--) {
revfac[i] = (revfac[i+1] * (i+1))%mod;
}
isBuild = true;
}
public long[] buildrui(int[] a) {
int n = a.length;
long[] ans = new long[n];
ans[0] = a[0];
for(int i=1;i<n;i++) {
ans[i] = ans[i-1] + a[i];
}
return ans;
}
public int[][] ibuildrui(int[][] a) {
int n = a.length;
int m = a[0].length;
int[][] ans = new int[n][m];
for(int i=1;i<n;i++) {
for(int j=1;j<m;j++) {
ans[i][j] = a[i][j];
}
}
for(int i=1;i<n;i++) {
for(int j=1;j<m;j++) {
ans[i][j] += ans[i][j-1] + ans[i-1][j] - ans[i-1][j-1];
}
}
return ans;
}
public void buildruin(int[][] a) {
int n = a.length;
int m = a[0].length;
for(int i=1;i<n;i++) {
for(int j=1;j<m;j++) {
a[i][j] += a[i][j-1] + a[i-1][j] - a[i-1][j-1];
}
}
}
public long[][] buildrui(int[][] a) {
int n = a.length;
int m = a[0].length;
long[][] ans = new long[n][m];
for(int i=1;i<n;i++) {
for(int j=1;j<m;j++) {
ans[i][j] = a[i][j];
}
}
for(int i=1;i<n;i++) {
for(int j=1;j<m;j++) {
ans[i][j] += ans[i][j-1] + ans[i-1][j] - ans[i-1][j-1];
}
}
return ans;
}
public int getrui(int[][] r,int a,int b,int c,int d) {
return r[c][d] - r[a-1][d] - r[c][b-1] + r[a-1][b-1];
}
public long getrui(long[][] r,int a,int b,int c,int d) {
if(a<0||b<0||c>=r.length||d>=r[0].length) return mod;
return r[c][d] - r[a-1][d] - r[c][b-1] + r[a-1][b-1];
}
long divroundup(long n,long d) {
if(n==0)return 0;
return (n-1)/d+1;
}
public long sigma(long i) {
return i*(i+1)/2;
}
public int digit(long i) {
int ans = 1;
while(i>=10) {
i /= 10;
ans++;
}
return ans;
}
public int digitsum(long n) {
int ans = 0;
while(n>0) {
ans += n%10;
n /= 10;
}
return ans;
}
public int popcount(int i) {
int ans = 0;
while(i>0) {
ans += i%2;
i /= 2;
}
return ans;
}
public boolean contains(int S,int i) {return (S>>i&1)==1;}
public int bitremove(int S,int i) {return S&(~(1<<i));}
public int bitadd(int S,int i) {return S|(1<<i);}
public boolean isSubSet(int S,int T) {return (S-T)==(S^T);}
public boolean isDisjoint(int S,int T) {return (S+T)==(S^T);}
public boolean contains(long S,int i) {return (S>>i&1)==1;}
public long bitremove(long S,int i) {return S&(~(1<<i));}
public long bitadd(long S,int i) {return S|(1<<i);}
public boolean isSubSet(long S,long T) {return (S-T)==(S^T);}
public boolean isDisjoint(long S,long T) {return (S+T)==(S^T);}
public int isBigger(int[] d, int i) {
int ok = d.length;
int ng = -1;
while(Math.abs(ok-ng)>1) {
int mid = (ok+ng)/2;
if(d[mid]>i) {
ok = mid;
}else {
ng = mid;
}
}
return ok;
}
public int isSmaller(int[] d, int i) {
int ok = -1;
int ng = d.length;
while(Math.abs(ok-ng)>1) {
int mid = (ok+ng)/2;
if(d[mid]<i) {
ok = mid;
}else {
ng = mid;
}
}
return ok;
}
public int isBigger(long[] d, long i) {
int ok = d.length;
int ng = -1;
while(Math.abs(ok-ng)>1) {
int mid = (ok+ng)/2;
if(d[mid]>i) {
ok = mid;
}else {
ng = mid;
}
}
return ok;
}
public int isSmaller(long[] d, long i) {
int ok = -1;
int ng = d.length;
while(Math.abs(ok-ng)>1) {
int mid = (ok+ng)/2;
if(d[mid]<i) {
ok = mid;
}else {
ng = mid;
}
}
return ok;
}
public int isBigger(ArrayList<Integer> d, int i) {
int ok = d.size();
int ng = -1;
while(Math.abs(ok-ng)>1) {
int mid = (ok+ng)/2;
if(d.get(mid)>i) {
ok = mid;
}else {
ng = mid;
}
}
return ok;
}
public int isSmaller(ArrayList<Integer> d, int i) {
int ok = -1;
int ng = d.size();
while(Math.abs(ok-ng)>1) {
int mid = (ok+ng)/2;
if(d.get(mid)<i) {
ok = mid;
}else {
ng = mid;
}
}
return ok;
}
public int isBigger(ArrayList<Long> d, long i) {
int ok = d.size();
int ng = -1;
while(Math.abs(ok-ng)>1) {
int mid = (ok+ng)/2;
if(d.get(mid)>i) {
ok = mid;
}else {
ng = mid;
}
}
return ok;
}
public int isSmaller(ArrayList<Long> d, long i) {
int ok = -1;
int ng = d.size();
while(Math.abs(ok-ng)>1) {
int mid = (ok+ng)/2;
if(d.get(mid)<i) {
ok = mid;
}else {
ng = mid;
}
}
return ok;
}
public HashSet<Integer> primetable(int m) {
HashSet<Integer> pt = new HashSet<Integer>();
for(int i=2;i<=m;i++) {
boolean b = true;
for(int d:pt) {
if(i%d==0) {
b = false;
break;
}
}
if(b) {
pt.add(i);
}
}
return pt;
}
public ArrayList<Integer> primetablearray(int m) {
ArrayList<Integer> al = new ArrayList<Integer>();
Queue<Integer> q = new ArrayDeque<Integer>();
for(int i=2;i<=m;i++) {
q.add(i);
}
boolean[] b = new boolean[m+1];
while(!q.isEmpty()) {
int e = q.poll();
if(!b[e]) {
al.add(e);
for(int j=1;e*j<=1000000;j++) {
b[e*j] = true;
}
}
}
return al;
}
public boolean isprime(int e) {
if(e==1) return false;
for(int i=2;i*i<=e;i++) {
if(e%i==0) return false;
}
return true;
}
public MultiSet Factrization(int e) {
MultiSet ret = new MultiSet();
for(int i=2;i*i<=e;i++) {
while(e%i==0) {
ret.add(i);
e /= i;
}
}
if(e!=1)ret.add(e);
return ret;
}
public int[] hipPush(int[] a){
int[] r = new int[a.length];
int[] s = new int[a.length];
for(int i=0;i<a.length;i++) {
s[i] = a[i];
}
Arrays.sort(s);
HashMap<Integer,Integer> m = new HashMap<Integer,Integer>();
for(int i=0;i<a.length;i++) {
m.put(s[i],i);
}
for(int i=0;i<a.length;i++) {
r[i] = m.get(a[i]);
}
return r;
}
public HashMap<Integer,Integer> hipPush(ArrayList<Integer> l){
HashMap<Integer,Integer> r = new HashMap<Integer,Integer>();
TreeSet<Integer> s = new TreeSet<Integer>();
for(int e:l)s.add(e);
int p = 0;
for(int e:s) {
r.put(e,p);
p++;
}
return r;
}
public TreeMap<Integer,Integer> thipPush(ArrayList<Integer> l){
TreeMap<Integer,Integer> r = new TreeMap<Integer,Integer>();
Collections.sort(l);
int b = -(1000000007+9393);
int p = 0;
for(int e:l) {
if(b!=e) {
r.put(e,p);
p++;
}
b=e;
}
return r;
}
int[] count(int[] a) {
int[] c = new int[max(a)+1];
for(int i=0;i<a.length;i++) {
c[a[i]]++;
}
return c;
}
int[] count(int[] a, int m) {
int[] c = new int[m+1];
for(int i=0;i<a.length;i++) {
c[a[i]]++;
}
return c;
}
long max(long[] a){
long M = Long.MIN_VALUE;
for(int i=0;i<a.length;i++){
if(M<=a[i]){
M =a[i];
maxdex = i;
}
}
return M;
}
int max(int[] a){
int M = Integer.MIN_VALUE;
for(int i=0;i<a.length;i++){
if(M<=a[i]){
M =a[i];
maxdex = i;
}
}
return M;
}
long min(long[] a){
long m = Long.MAX_VALUE;
for(int i=0;i<a.length;i++){
if(m>a[i]){
m =a[i];
mindex = i;
}
}
return m;
}
int min(int[] a){
int m = Integer.MAX_VALUE;
for(int i=0;i<a.length;i++){
if(m>a[i]){
m =a[i];
mindex = i;
}
}
return m;
}
long sum(long[] a){
long s = 0;
for(int i=0;i<a.length;i++)s += a[i];
return s;
}
long sum(int[] a){
long s = 0;
for(int i=0;i<a.length;i++)s += a[i];
return s;
}
long sum(ArrayList<Integer> l) {
long s = 0;
for(int e:l)s += e;
return s;
}
long gcd(long a, long b){
a = Math.abs(a);
b = Math.abs(b);
if(a==0)return b;
if(b==0)return a;
if(a%b==0) return b;
else return gcd(b,a%b);
}
int igcd(int a, int b) {
if(a%b==0) return b;
else return igcd(b,a%b);
}
long lcm(long a, long b) {return a / gcd(a,b) * b;}
public long perm(int a,int num) {
if(!isBuild)buildFac();
return fac[a]*(rev(fac[a-num]))%mod;
}
void buildComb(int N) {
comb = new long[N+1][N+1];
comb[0][0] = 1;
for(int i=1;i<=N;i++) {
comb[i][0] = 1;
for(int j=1;j<N;j++) {
comb[i][j] = comb[i-1][j-1]+comb[i-1][j];
if(comb[i][j]>mod)comb[i][j]-=mod;
}
comb[i][i] = 1;
}
}
public long comb(int a,int num){
if(a-num<0)return 0;
if(num<0)return 0;
if(!isBuild)buildFac();
if(a>10000000) return combN(a,num);
return fac[a] * ((revfac[num]*revfac[a-num])%mod)%mod;
}
long combN(int a,int num) {
long ans = 1;
for(int i=0;i<num;i++) {
ans *= a-i;
ans %= mod;
}
return ans * revfac[num] % mod;
}
long mulchoose(int n,int k) {
if(k==0) return 1;
return comb(n+k-1,k);
}
long rev(long l) {return pow(l,mod-2);}
void buildpow(int l,int i) {
pow = new long[i+1];
pow[0] = 1;
for(int j=1;j<=i;j++) {
pow[j] = pow[j-1]*l;
if(pow[j]>mod)pow[j] %= mod;
}
}
void buildrevpow(int l,int i) {
revpow = new long[i+1];
revpow[0] = 1;
for(int j=1;j<=i;j++) {
revpow[j] = revpow[j-1]*l;
if(revpow[j]>mod) revpow[j] %= mod;
}
}
long pow(long l, long i) {
if(i==0)return 1;
else{
if(i%2==0){
long val = pow(l,i/2);
return val * val % mod;
}
else return pow(l,i-1) * l % mod;
}
}
long mon(int i) {
long ans = 0;
for(int k=2;k<=i;k++) {
ans += (k%2==0?1:-1) * revfac[k];
ans += mod;
}
ans %= mod;
ans *= fac[i];
return ans%mod;
}
long dictnum(int[] A) {
int N = A.length;
long ans = 0;
BinaryIndexedTree bit = new BinaryIndexedTree(N+1);
buildFacn(N);
for(int i=1;i<=N;i++) {
bit.add(i,1);
}
for(int i=1;i<=N;i++) {
int a = A[i-1];
ans += bit.sum(a-1) * fac[N-i] % mod;
bit.add(a,-1);
}
return (ans+1)%mod;
}
}
| JAVA |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public int MAXD = 1000010;
public List<TaskB.Flight>[] fs;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt(), m = in.nextInt(), k = in.nextInt();
fs = LUtils.genArrayList(MAXD);
for (int i = 0; i < m; i++) {
int d = in.nextInt(), f = in.nextInt(), t = in.nextInt(), c = in.nextInt();
if (f == 0)
fs[d].add(new TaskB.Flight(t, c, false));
else
fs[d].add(new TaskB.Flight(f, c, true));
}
long[] fx = new long[MAXD + 1];
boolean[] vf = new boolean[MAXD + 1];
{
long[] pc = new long[n + 1];
Arrays.fill(pc, 1 << 29);
int count = 0;
pc[0] = 0;
fx[0] = AUtils.sum(pc);
vf[0] = false;
for (int i = 0; i < MAXD; i++) {
fx[i + 1] = fx[i];
for (TaskB.Flight ff : fs[i]) {
if (!ff.dir) continue;
if (ff.cost < pc[ff.person]) {
if (pc[ff.person] == 1 << 29) count++;
fx[i + 1] -= pc[ff.person];
pc[ff.person] = ff.cost;
fx[i + 1] += pc[ff.person];
}
}
vf[i + 1] = count == n;
}
}
long[] bx = new long[MAXD + 1];
boolean[] vb = new boolean[MAXD + 1];
{
long[] pc = new long[n + 1];
Arrays.fill(pc, 1 << 29);
int count = 0;
pc[0] = 0;
bx[MAXD] = AUtils.sum(pc);
vb[MAXD] = false;
for (int i = MAXD - 1; i >= 0; i--) {
bx[i] = bx[i + 1];
for (TaskB.Flight ff : fs[i]) {
if (ff.dir) continue;
if (ff.cost < pc[ff.person]) {
if (pc[ff.person] == 1 << 29) count++;
bx[i] -= pc[ff.person];
pc[ff.person] = ff.cost;
bx[i] += pc[ff.person];
}
}
vb[i] = count == n;
}
}
long ret = 1L << 60;
for (int i = 0; i + k < MAXD; i++) {
if (vf[i] && vb[i + k])
ret = Math.min(ret, fx[i] + bx[i + k]);
}
out.println(ret >= 1L << 60 ? -1 : ret);
}
static class Flight {
public int person;
public int cost;
public boolean dir;
public Flight(int person, int cost, boolean dir) {
this.person = person;
this.cost = cost;
this.dir = dir;
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (this.numChars == -1) {
throw new InputMismatchException();
} else {
if (this.curChar >= this.numChars) {
this.curChar = 0;
try {
this.numChars = this.stream.read(this.buf);
} catch (IOException var2) {
throw new InputMismatchException();
}
if (this.numChars <= 0) {
return -1;
}
}
return this.buf[this.curChar++];
}
}
public int nextInt() {
int c;
for (c = this.read(); isSpaceChar(c); c = this.read()) {
;
}
byte sgn = 1;
if (c == 45) {
sgn = -1;
c = this.read();
}
int res = 0;
while (c >= 48 && c <= 57) {
res *= 10;
res += c - 48;
c = this.read();
if (isSpaceChar(c)) {
return res * sgn;
}
}
throw new InputMismatchException();
}
public static boolean isSpaceChar(int c) {
return c == 32 || c == 10 || c == 13 || c == 9 || c == -1;
}
}
static class LUtils {
public static <E> List<E>[] genArrayList(int size) {
return Stream.generate(ArrayList::new).limit(size).toArray(List[]::new);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(long i) {
writer.println(i);
}
}
static class AUtils {
public static long sum(long[] arr) {
long sum = 0;
for (long x : arr) {
sum += x;
}
return sum;
}
}
}
| JAVA |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int N = 1000100;
vector<pair<int, int> > e0[N], e1[N];
int v0[N], v1[N], ml, mr;
long long s0[N], s1[N];
int main() {
int n, m, k;
scanf("%d%d%d", &n, &m, &k);
for (register int i = 1; i <= m; i++) {
int d, f, t, c;
scanf("%d%d%d%d", &d, &f, &t, &c);
if (!t)
e0[d].push_back(make_pair(f, c));
else
e1[d].push_back(make_pair(t, c));
}
int cnt = 0;
for (register int i = 1; i <= 1e6; i++) {
s0[i] = s0[i - 1];
if (e0[i].size())
for (register int j = 0; j <= e0[i].size() - 1; j++) {
int tmp = e0[i][j].first;
if (!v0[tmp]) {
v0[tmp] = e0[i][j].second, s0[i] += e0[i][j].second;
if (++cnt == n) ml = i;
} else if (v0[tmp] > e0[i][j].second)
s0[i] += e0[i][j].second - v0[tmp], v0[tmp] = e0[i][j].second;
}
}
cnt = 0;
for (int i = 1e6; i; i--) {
s1[i] = s1[i + 1];
if (e1[i].size())
for (register int j = 0; j <= e1[i].size() - 1; j++) {
int tmp = e1[i][j].first;
if (!v1[tmp]) {
v1[tmp] = e1[i][j].second, s1[i] += e1[i][j].second;
if (++cnt == n) mr = i;
} else if (v1[tmp] > e1[i][j].second)
s1[i] += e1[i][j].second - v1[tmp], v1[tmp] = e1[i][j].second;
}
}
if (!ml || !mr)
printf("-1\n");
else {
long long ans = 1e18;
for (int i = ml + 1; i + k - 1 < mr; i++)
ans = min(ans, s0[i - 1] + s1[i + k]);
if (ans == 1e18)
printf("-1\n");
else
printf("%lld\n", ans);
}
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int fastMax(int x, int y) { return (((y - x) >> (32 - 1)) & (x ^ y)) ^ y; }
int fastMin(int x, int y) { return (((y - x) >> (32 - 1)) & (x ^ y)) ^ x; }
const long long int MAXN = 1e5 + 10;
long long int d[MAXN], first[MAXN], t[MAXN], c[MAXN];
long long int ind[MAXN];
const long long int MAXM = 1e6 + 10;
bool cmp(long long int a, long long int b) {
if (d[a] == d[b]) {
if (c[a] == c[b]) {
if (first[a] == first[b]) {
return t[a] < t[b];
}
return first[a] < first[b];
}
return c[a] < c[b];
} else
return d[a] < d[b];
}
long long int entry[MAXM];
long long int entry_particular[MAXN];
long long int exitx[MAXM];
long long int exit_particular[MAXN];
void solve() {
long long int n, m, k;
cin >> n >> m >> k;
for (long long int i = (1); i <= (m); ++i) {
cin >> d[i] >> first[i] >> t[i] >> c[i];
ind[i] = i;
}
sort(ind + 1, ind + m + 1, cmp);
for (long long int i = (1); i <= (n); ++i) {
entry_particular[i] = 1e12;
entry[0] += entry_particular[i];
}
long long int idx = 1;
for (long long int i = (1); i <= (MAXM - 1); ++i) {
entry[i] = entry[i - 1];
while (idx <= m && d[ind[idx]] <= i) {
if (t[ind[idx]] == 0) {
entry[i] -= entry_particular[first[ind[idx]]];
entry_particular[first[ind[idx]]] =
min(entry_particular[first[ind[idx]]], c[ind[idx]]);
entry[i] += entry_particular[first[ind[idx]]];
}
idx++;
}
}
for (long long int i = (1); i <= (n); ++i) {
exit_particular[i] = 1e12;
exitx[MAXM - 1] += exit_particular[i];
}
idx = m;
for (long long int i = (MAXM - 2); i >= (0); --i) {
exitx[i] = exitx[i + 1];
while (idx >= 1 && d[ind[idx]] >= i) {
if (first[ind[idx]] == 0) {
exitx[i] -= exit_particular[t[ind[idx]]];
exit_particular[t[ind[idx]]] =
min(exit_particular[t[ind[idx]]], c[ind[idx]]);
exitx[i] += exit_particular[t[ind[idx]]];
}
idx--;
}
}
long long int ans = 1e12;
idx = 1;
while (1) {
long long int j = idx + k - 1;
if (j >= MAXM - 1) break;
ans = min(ans, entry[idx - 1] + exitx[j + 1]);
idx++;
}
if (ans == 1e12)
cout << -1 << '\n';
else
cout << ans << '\n';
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
;
long long int t;
t = 1;
for (long long int i = (1); i <= (t); ++i) {
solve();
}
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
struct N {
int d, a, b, c;
bool operator<(const N ot) const { return c > ot.c; }
};
int n, m, k;
N v[100005];
priority_queue<N> pq[100005];
bitset<1000005> pos;
long long mn[1000005];
void salida() {
long long acu = 0;
int c = 0, j = 1;
for (int i = 1; i <= n; i++) {
if (pq[i].size()) {
acu += pq[i].top().c;
c++;
}
}
for (int i = 0; i < m; i++) {
if (v[i].b) {
priority_queue<N> &q = pq[v[i].b];
while (j <= v[i].d - k) {
mn[j] = acu;
pos[j] = c == n;
j++;
}
while (q.size() && q.top().d <= v[i].d) {
acu -= q.top().c;
q.pop();
if (q.size()) {
acu += q.top().c;
} else {
c--;
}
}
}
}
}
long long entrada() {
long long acu = 0;
int cit[100005];
int c = 0, j = 0;
fill(cit + 1, cit + 1 + n, 1e9);
for (int i = 0; i < m; i++) {
if (v[i].a) {
while (j <= v[i].d) {
mn[j] += acu;
pos[j] = pos[j] && (c == n);
j++;
}
if (cit[v[i].a] == 1e9) {
cit[v[i].a] = v[i].c;
c++;
acu += v[i].c;
}
acu -= cit[v[i].a];
cit[v[i].a] = min(cit[v[i].a], v[i].c);
acu += cit[v[i].a];
}
}
while (j < 1e6) {
mn[j] += acu;
pos[j] = pos[j] && (c == n);
j++;
}
long long res = 1e18;
for (int i = 1; i <= 1e6; i++)
if (pos[i]) res = min(res, mn[i]);
return res == 1e18 ? -1 : res;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m >> k;
for (int i = 0; i < m; i++) {
cin >> v[i].d >> v[i].a >> v[i].b >> v[i].c;
if (v[i].b) pq[v[i].b].push(v[i]);
}
sort(v, v + m, [&](N a, N b) { return a.d < b.d; });
salida();
cout << entrada() << '\n';
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
const int N = 1e6 + 10;
using namespace std;
int n, m, k;
bool ok[N];
long long costi[N];
long long costo[N];
long long in[N];
long long out[N];
bool S[N], E[N];
struct node {
int d, s, e, w;
node() {}
node(int dd, int ss, int ee, int ww) {
d = dd;
s = ss;
e = ee;
w = ww;
}
} A[N];
bool cmp(node a, node b) { return a.d < b.d; }
int main() {
scanf("%d%d%d", &n, &m, &k);
for (int i = 0; i < m; ++i)
scanf("%d%d%d%d", &A[i].d, &A[i].s, &A[i].e, &A[i].w);
sort(A, A + m, cmp);
int cnt = 0, j = 0;
for (int i = 1; i < N; ++i) {
costi[i] = costi[i - 1];
S[i] = S[i - 1];
while (j < m && A[j].d == i) {
node t = A[j++];
if (t.e) continue;
costi[i] -= in[t.s];
if (!ok[t.s]) {
ok[t.s] = 1;
++cnt;
in[t.s] = t.w;
} else {
in[t.s] = min(in[t.s], (long long)t.w);
}
costi[i] += in[t.s];
}
if (cnt == n) S[i] = 1;
}
memset(ok, 0, sizeof(ok));
cnt = 0;
j = m - 1;
for (int i = 1000000; i; --i) {
costo[i] = costo[i + 1];
E[i] = E[i + 1];
while (j >= 0 && i == A[j].d) {
node t = A[j--];
if (t.s) continue;
costo[i] -= out[t.e];
if (!ok[t.e]) {
ok[t.e] = true;
++cnt;
out[t.e] = t.w;
} else {
out[t.e] = min(out[t.e], (long long)t.w);
}
costo[i] += out[t.e];
}
if (cnt == n) E[i] = 1;
}
long long ans = 1e18;
for (int i = 1, j = i + k + 1; j < N; ++i, ++j) {
if (S[i] && E[j]) ans = min(ans, costi[i] + costo[j]);
}
if (ans >= 1e17) {
printf("-1\n");
} else
printf("%I64d\n", ans);
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int N = 100000;
const int M = 1000000;
const int INF = 1000001;
struct flight_t {
int date, idx, cost;
flight_t() = default;
flight_t(const int& date, const int& idx, const int& cost)
: date(date), idx(idx), cost(cost) {}
bool operator<(const flight_t& that) const { return date < that.date; }
bool operator>(const flight_t& that) const { return date > that.date; }
};
typedef priority_queue<flight_t, vector<flight_t>, greater<flight_t>>
flight_min_pq;
flight_min_pq inflight;
priority_queue<flight_t> outflight;
int in_per[N + 1], out_per[N + 1];
long long min_in[M + 1], min_out[M + 1];
int main() {
int n, m, k;
scanf("%d%d%d", &n, &m, &k);
while (m--) {
int date, u, v, cost;
scanf("%d%d%d%d", &date, &u, &v, &cost);
if (v == 0) {
inflight.emplace(date, u, cost);
}
if (u == 0) {
outflight.emplace(date, v, cost);
}
}
fill(in_per + 1, in_per + N + 1, 0);
fill(min_in + 1, min_in + M + 1, 1LL * N * INF);
int cnt = 0;
long long total_cost = 0LL;
for (int i = 1; i <= M - k - 1; ++i) {
while (!inflight.empty()) {
int date = inflight.top().date, u = inflight.top().idx,
cost = inflight.top().cost;
if (date > i) break;
inflight.pop();
if (!in_per[u]) {
++cnt;
total_cost += cost;
in_per[u] = cost;
} else if (in_per[u] > cost) {
total_cost -= in_per[u] - cost;
in_per[u] = cost;
}
}
if (cnt == n) {
min_in[i] = min(min_in[i], total_cost);
}
}
fill(out_per + 1, out_per + N + 1, 0);
fill(min_out + 1, min_out + M + 1, 1LL * N * INF);
cnt = 0;
total_cost = 0LL;
for (int i = M; i >= k + 2; --i) {
while (!outflight.empty()) {
int date = outflight.top().date, v = outflight.top().idx,
cost = outflight.top().cost;
if (date < i) break;
outflight.pop();
if (!out_per[v]) {
++cnt;
total_cost += cost;
out_per[v] = cost;
} else if (out_per[v] > cost) {
total_cost -= out_per[v] - cost;
out_per[v] = cost;
}
}
if (cnt == n) {
min_out[i] = min(min_out[i], total_cost);
}
}
long long total_min = 2LL * N * INF;
for (int i = 1; i <= M - k - 1; ++i) {
if (min_in[i] == 1LL * N * INF || min_out[i + k + 1] == 1LL * N * INF)
continue;
total_min = min(total_min, min_in[i] + min_out[i + k + 1]);
}
printf("%lld\n", (total_min < 2LL * N * INF) ? total_min : -1);
exit(EXIT_SUCCESS);
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
vector<pair<pair<long long, long long>, pair<long long, long long>>> q;
long long const inf = 1e17;
long long const N = 1e6 + 10;
long long pre[N];
long long suf[N];
vector<pair<long long, long long>> Df[N], Db[N];
long long costto[N];
signed main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
;
long long n, m, k;
cin >> n >> m >> k;
for (long long i = 0; i < m; i++) {
long long d, first, t, c;
cin >> d >> first >> t >> c;
q.push_back({{d, first}, {t, c}});
if (t == 0)
Df[d + 1].push_back({first, c});
else {
Db[d - 1].push_back({t, c});
}
}
for (long long i = 0; i < N; i++) {
costto[i] = inf;
}
long long tot = 0;
set<long long> second;
pre[0] = inf;
for (long long i = 1; i < N; i++) {
pre[i] = min(pre[i - 1], inf);
for (auto x : Df[i]) {
second.insert(x.first);
if (costto[x.first] != inf) {
if (costto[x.first] > x.second) {
tot -= costto[x.first];
tot += x.second;
costto[x.first] = x.second;
}
} else {
costto[x.first] = x.second;
tot += x.second;
}
}
if (second.size() == n) {
pre[i] = tot;
}
}
for (long long i = 0; i < N; i++) {
costto[i] = inf;
}
second.clear();
tot = 0;
suf[N - 1] = inf;
for (long long i = N - 2; i >= 0; i--) {
suf[i] = min(suf[i + 1], inf);
for (auto x : Db[i]) {
second.insert(x.first);
if (costto[x.first] != inf) {
if (costto[x.first] > x.second) {
tot -= costto[x.first];
tot += x.second;
costto[x.first] = x.second;
}
} else {
costto[x.first] = x.second;
tot += x.second;
}
}
if (second.size() == n) {
suf[i] = tot;
}
}
long long ans = inf;
for (long long i = 0; i < N; i++) {
if (i + k > N) break;
ans = min(ans, pre[i] + suf[i + k - 1]);
}
if (ans == inf) {
cout << "-1\n";
} else {
cout << ans << endl;
}
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
struct Flight {
int d, s, t, c;
bool operator<(const Flight &o) const { return d < o.d; }
};
int ct[100008];
long long int d1[100008];
long long int d2[100008];
Flight fl[100008];
int main() {
int C, F, D, n, i, j;
long long int c;
scanf("%d %d %d", &C, &F, &D);
for (i = 0; i < F; i++) {
Flight &fi = fl[i];
scanf("%d %d %d %d", &fi.d, &fi.s, &fi.t, &fi.c);
}
sort(fl, fl + F);
n = 0;
c = 0;
for (i = 0; i < F; i++) {
const Flight &fi = fl[i];
if (fi.t == 0)
if (ct[fi.s] == 0) {
ct[fi.s] = fi.c;
c += ct[fi.s];
n++;
} else if (ct[fi.s] > fi.c) {
c -= ct[fi.s];
ct[fi.s] = fi.c;
c += ct[fi.s];
}
if (n == C) d1[i] = c;
}
memset(ct, 0, sizeof ct);
n = 0;
c = 0;
for (i = F - 1; i >= 0; i--) {
const Flight &fi = fl[i];
if (fi.s == 0)
if (ct[fi.t] == 0) {
ct[fi.t] = fi.c;
c += ct[fi.t];
n++;
} else if (ct[fi.t] > fi.c) {
c -= ct[fi.t];
ct[fi.t] = fi.c;
c += ct[fi.t];
}
if (n == C) d2[i] = c;
}
long long int A = -1;
for (i = 0, j = 0; i < F; i++) {
while (j < F && fl[i].d + D >= fl[j].d) j++;
if (j < F && d1[i] != 0 && d2[j] != 0)
if (A < 0 || A > d1[i] + d2[j]) A = d1[i] + d2[j];
}
printf(
"%I64d"
"\n",
A);
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;
int n, m, k;
struct F {
int u, cost;
};
vector<F> to0[maxn], left0[maxn];
int d, u, v, cost, mxt;
long long mn[maxn];
long long arr[maxn], dep[maxn];
int main() {
scanf("%d%d%d", &n, &m, &k);
for (int i = 1; i <= m; ++i) {
scanf("%d%d%d%d", &d, &u, &v, &cost);
mxt = max(mxt, d);
if (u)
to0[d].push_back((F){u, cost});
else
left0[d].push_back((F){v, cost});
}
for (int i = 1; i <= n; ++i) {
mn[i] = 1000000000000ll;
arr[0] += mn[i];
dep[mxt + 1] += mn[i];
}
for (int i = 1; i <= mxt; ++i) {
arr[i] = arr[i - 1];
int l = to0[i].size();
for (int j = 0; j < l; ++j) {
int nu = to0[i][j].u;
if (to0[i][j].cost < mn[nu])
arr[i] -= mn[nu], arr[i] += to0[i][j].cost, mn[nu] = to0[i][j].cost;
}
}
for (int i = 1; i <= n; ++i) mn[i] = 1000000000000ll;
for (int i = mxt; i >= 1; --i) {
dep[i] = dep[i + 1];
int l = left0[i].size();
for (int j = 0; j < l; ++j) {
int nv = left0[i][j].u;
if (left0[i][j].cost < mn[nv])
dep[i] -= mn[nv], dep[i] += left0[i][j].cost, mn[nv] = left0[i][j].cost;
}
}
long long ans = 0x3f3f3f3f3f3f3f3f;
for (int i = 1; i <= mxt - k - 1; ++i) {
ans = min(ans, arr[i] + dep[i + k + 1]);
}
if (ans > 1e11)
puts("-1");
else
printf("%lld", ans);
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 7;
tuple<int, int, int> t[maxn];
multiset<long long> h[maxn];
const long long inf = 0x3f3f3f3f3f;
long long mn[maxn];
int n, m, k;
int main() {
scanf("%d%d%d", &n, &m, &k);
for (int i = 0; i < m; i++) {
int d, u, v, c;
scanf("%d%d%d%d", &d, &u, &v, &c);
if (v == 0)
t[i] = make_tuple(d, u, c);
else {
t[i] = make_tuple(d, -v, c);
h[v].insert(c);
}
}
sort(t, t + m);
long long ans = inf * 2;
long long lsum = 0, rsum = 0;
for (int i = 1; i <= n; i++) {
mn[i] = inf;
lsum += inf;
h[i].insert(inf);
rsum += *h[i].begin();
}
int l = 0, r = 0;
for (int e = 1; e <= 1e6; e++) {
while (l < m && get<0>(t[l]) < e) {
int now = get<1>(t[l]);
if (now > 0) {
lsum -= mn[now];
mn[now] = min(mn[now], (long long)get<2>(t[l]));
lsum += mn[now];
}
l++;
}
while (r < m && get<0>(t[r]) < e + k) {
int now = -get<1>(t[r]);
if (now > 0) {
rsum -= *h[now].begin();
h[now].erase(h[now].find(get<2>(t[r])));
rsum += *h[now].begin();
}
r++;
}
ans = min(ans, lsum + rsum);
}
if (ans >= inf)
printf("-1\n");
else
printf("%I64d", ans);
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int MAX = 1 << 20;
const long long INF = 1e12;
int dan[MAX], poc[MAX], kraj[MAX], cost[MAX];
long long pref[MAX], suf[MAX];
vector<pair<int, int> > Tamo[MAX], Nazad[MAX];
int nope() {
printf("-1\n");
exit(0);
}
int main() {
int n, m, k;
scanf("%d%d%d", &n, &m, &k);
for (int i = 0; i < m; i++) {
scanf("%d%d%d%d", &dan[i], &poc[i], &kraj[i], &cost[i]);
if (poc[i] == 0)
Nazad[kraj[i]].push_back(pair<int, int>(dan[i], cost[i]));
else
Tamo[poc[i]].push_back(pair<int, int>(dan[i], cost[i]));
}
for (int i = (1); i < (n + 1); i++) {
sort(Tamo[i].begin(), Tamo[i].end());
sort(Nazad[i].begin(), Nazad[i].end(), greater<pair<int, int> >());
if (Tamo[i].empty()) nope();
if (Nazad[i].empty()) nope();
long long minn = INF;
pref[0] += minn;
for (auto it : Tamo[i]) {
if (it.second < minn) pref[it.first + 1] += it.second - minn;
minn = min(minn, (long long)it.second);
}
minn = INF;
suf[MAX - 1] += minn;
for (auto it : Nazad[i]) {
if (it.second < minn) suf[it.first - 1] += it.second - minn;
minn = min(minn, (long long)it.second);
}
}
for (int i = (1); i < (MAX); i++) pref[i] += pref[i - 1];
for (int i = MAX - 2; i >= 0; i--) suf[i] += suf[i + 1];
long long rje = INF;
for (int p = (1); p < (MAX); p++) {
int kr = p + k - 1;
if (kr >= MAX) break;
rje = min(rje, pref[p] + suf[kr]);
}
if (rje >= INF) nope();
cout << rje << endl;
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
struct node {
int day, from, to, cost;
};
const bool operator<(node a, node b) {
if (a.day < b.day) return 1;
return 0;
}
struct triple {
int first, second, th;
};
const bool operator<(triple a, triple b) {
if (a.first < b.first) return 1;
if (a.first > b.first) return 0;
if (a.second < b.second) return 1;
if (a.second > b.second) return 0;
if (a.th < b.th) return 1;
return 0;
}
vector<int> pos[1000001];
vector<node> a;
int sum[1000001];
map<triple, int> is;
int n;
int print(long long ans) {
for (int i = 1; i <= n; i++)
if (sum[i] == (int)1e9) return cout << -1, 0;
cout << ans;
return 0;
}
int main() {
(("" != "") ? (freopen(""
".in",
"r", stdin),
freopen(""
".out",
"w", stdout))
: (0));
int m, k;
cin >> n >> m >> k;
for (int i = 0; i < m; i++) {
int day, from, to, cost;
cin >> day >> from >> to >> cost;
if (is[{day, from, to}] != 0)
is[{day, from, to}] = min(is[{day, from, to}], cost);
else
is[{day, from, to}] = cost;
}
for (auto i : is)
a.push_back({i.first.first, i.first.second, i.first.th, i.second});
long long cnt = 0;
int x = -1;
for (int i = a.size() - 1; i >= 0; i--)
if (a[i].from == 0 && a[i].day >= k + 1) {
x = i;
if (!pos[a[i].to].empty())
cnt -= pos[a[i].to].back(), pos[a[i].to].push_back(pos[a[i].to].back());
else
pos[a[i].to].push_back(1e9);
pos[a[i].to].back() = min(pos[a[i].to].back(), a[i].cost);
cnt += pos[a[i].to].back();
}
for (int i = 1; i <= n; i++)
if (pos[i].empty()) return cout << -1, 0;
for (int i = 1; i <= n; i++) sum[i] = 1e9;
long long sol = n * (long long)1e9, ans = sol;
for (int i = 0; i < m; i++)
if (a[i].from != 0) {
while (x < a.size() && a[i].day + k + 1 > a[x].day) {
if (a[x].from == 0) {
cnt -= pos[a[x].to].back();
pos[a[x].to].pop_back();
if (pos[a[x].to].empty()) return print(ans);
cnt += pos[a[x].to].back();
}
x++;
}
sol -= sum[a[i].from];
sum[a[i].from] = min(sum[a[i].from], a[i].cost);
sol += sum[a[i].from];
ans = min(ans, cnt + sol);
}
print(ans);
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
long long val[112345], valf[112345];
struct node {
int d, f, t, c;
node() {}
node(int d, int f, int t, int c) : d(d), f(f), t(t), c(c) {}
void print() { printf("%d %d %d %d\n", d, f, t, c); }
} flightTo[112345], flightFrom[112345];
struct node2 {
int t;
long long s;
node2() {}
node2(int t, long long s) : t(t), s(s) {}
bool operator<(const node2 &N) const {
if (t == N.t) return s < N.s;
return t < N.t;
}
};
bool cmpto(node x, node y) { return x.d < y.d; }
bool cmpfrom(node x, node y) { return x.d > y.d; }
int main() {
int n, m, k;
scanf("%d%d%d", &n, &m, &k);
int cntto = 0, cntfrom = 0;
for (int i = 1; i <= m; i++) {
int d, f, t, c;
scanf("%d%d%d%d", &d, &f, &t, &c);
if (t) {
flightFrom[cntfrom++] = node(d, f, t, c);
} else {
flightTo[cntto++] = node(d, f, t, c);
}
}
sort(flightTo, flightTo + cntto, cmpto);
sort(flightFrom, flightFrom + cntfrom, cmpfrom);
int cnt = 0;
long long sum = 0;
vector<node2> vto;
for (int i = 0; i < cntto; i++) {
node nt = flightTo[i];
bool update = 0;
if (val[nt.f] == 0) {
cnt++;
val[nt.f] = nt.c;
sum += nt.c;
update = 1;
} else if (val[nt.f] > nt.c) {
sum = sum - val[nt.f] + nt.c;
val[nt.f] = nt.c;
update = 1;
}
if (update && cnt == n) {
vto.push_back(node2(nt.d, sum));
}
}
int cntf = 0;
long long sumf = 0;
vector<node2> vfr;
for (int i = 0; i < cntfrom; i++) {
node nt = flightFrom[i];
bool update = 0;
if (valf[nt.t] == 0) {
cntf++;
valf[nt.t] = nt.c;
sumf += nt.c;
update = 1;
} else if (valf[nt.t] > nt.c) {
sumf = sumf - valf[nt.t] + nt.c;
valf[nt.t] = nt.c;
update = 1;
}
if (update && cntf == n) {
vfr.push_back(node2(nt.d, sumf));
}
}
sort(vfr.begin(), vfr.end());
long long ans = -1;
for (int i = 0; i < vto.size(); i++) {
node2 nt = vto[i];
auto it = lower_bound(vfr.begin(), vfr.end(), node2(nt.t + k + 1, -1));
if (it == vfr.end()) continue;
if (ans < 0)
ans = vto[i].s + (*it).s;
else
ans = min(ans, vto[i].s + (*it).s);
}
printf("%I64d\n", ans);
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int n, m, k;
pair<pair<int, int>, pair<int, int> > a[100005];
int sl[100005], sr[100005], pl = 1000000, pr;
long long l[1000005], r[1000005];
int ll, rr;
int main() {
scanf("%d%d%d", &n, &m, &k);
for (int i = 1; i <= m; i++) {
scanf("%d%d%d%d", &a[i].first.first, &a[i].first.second, &a[i].second.first,
&a[i].second.second);
}
sort(&a[1], &a[m + 1]);
for (int i = 1; i <= n; i++) sl[i] = 1000001, l[0] += sl[i];
ll = n;
int j = 1;
for (int i = 1; i <= 1000000; i++) {
l[i] = l[i - 1];
while (a[j].first.first == i && j <= m) {
if (a[j].first.second) {
int t = a[j].first.second;
if (sl[t] == 1000001)
ll--, l[i] -= sl[t] - a[j].second.second, sl[t] = a[j].second.second;
else if (sl[t] > a[j].second.second)
l[i] -= sl[t] - a[j].second.second, sl[t] = a[j].second.second;
}
j++;
}
if (ll == 0) pl = min(pl, i);
}
for (int i = 1; i <= n; i++) sr[i] = 1000001, r[1000001] += sr[i];
rr = n;
j = m;
for (int i = 1000000; i >= 1; i--) {
r[i] = r[i + 1];
while (a[j].first.first == i && j) {
if (a[j].second.first) {
int t = a[j].second.first;
if (sr[t] == 1000001)
rr--, r[i] -= sr[t] - a[j].second.second, sr[t] = a[j].second.second;
else if (sr[t] > a[j].second.second)
r[i] -= sr[t] - a[j].second.second, sr[t] = a[j].second.second;
}
j--;
}
if (rr == 0) pr = max(i, pr);
}
long long ans = (1ll << 60);
for (int i = pl; i + k + 1 <= pr; i++) ans = min(ans, l[i] + r[i + k + 1]);
cout << (ans == (1ll << 60) ? -1 : ans) << endl;
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | import java.io.BufferedInputStream;
import java.util.*;
/**
* Created by leen on 23/09/2017.
*/
public class _853B {
public static void main(String[] args) {
Scanner scan = new Scanner(new BufferedInputStream(System.in, 1024*1024));
int n = scan.nextInt(), m = scan.nextInt(), k = scan.nextInt();
if(m < n * 2) {
System.out.println(-1);
return;
}
List<Flight> arriveFlights = new ArrayList<>();
List<Flight> departFlights = new ArrayList<>();
for(int i = 0; i < m; i++) {
int day = scan.nextInt(), departCity = scan.nextInt(), arriveCity = scan.nextInt(), cost = scan.nextInt();
Flight flight = new Flight(day, departCity == 0 ? arriveCity : departCity, cost);
if(departCity == 0)
departFlights.add(flight);
else
arriveFlights.add(flight);
}
if(arriveFlights.size() < n || departFlights.size() < n) {
System.out.println(-1);
return;
}
arriveFlights.sort(Comparator.comparingInt(a -> a.day));
departFlights.sort(Comparator.comparingInt(a -> -a.day));
Cost[] arriveCosts = buildTotalCosts(arriveFlights, n);
Cost[] departCosts = buildTotalCosts(departFlights, n);
if(arriveCosts.length == 0 || departCosts.length == 0) {
System.out.println(-1);
return;
}
long minTotalCost = -1L;
for(int p = 0, q = departCosts.length - 1; p < arriveCosts.length; p++) {
for(; q >= 0 && departCosts[q].day - arriveCosts[p].day <= k; q--);
if(q < 0)
break;
for(; p < arriveCosts.length-1 && departCosts[q].day - arriveCosts[p+1].day > k; p++);
if(minTotalCost == -1L) {
minTotalCost = arriveCosts[p].cost + departCosts[q].cost;
}
else {
minTotalCost = Math.min(minTotalCost, arriveCosts[p].cost + departCosts[q].cost);
}
}
System.out.println(minTotalCost);
}
private static Cost[] buildTotalCosts(List<Flight> flights, int n) {
long totalCost = 0L;
List<Cost> totalCosts = new ArrayList<>();
int[] city2cost = new int[n+1];
int numCities = 0;
Cost lastCost = null;
for(Flight flight : flights) {
Integer oldCost = city2cost[flight.city];
if(oldCost == 0)
numCities++;
else if(oldCost <= flight.cost)
continue;
city2cost[flight.city] = flight.cost;
totalCost += flight.cost - oldCost;
if(numCities == n) {
if(lastCost != null && lastCost.day == flight.day) {
lastCost.cost = totalCost;
}
else {
lastCost = new Cost(flight.day, totalCost);
totalCosts.add(lastCost);
}
}
}
Cost[] costs = new Cost[totalCosts.size()];
totalCosts.toArray(costs);
return costs;
}
private static class Flight {
final int city;
final int day;
final int cost;
Flight(int day, int city , int cost) {
this.city = city;
this.day = day;
this.cost = cost;
}
}
private static class Cost {
final int day;
long cost;
Cost(int day, long cost) {
this.day= day;
this.cost = cost;
}
}
}
| JAVA |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
const int INF = 0x3f3f3f3f;
const long long llINF = 0x3f3f3f3f3f3f3f3f;
const int mod = 998244353;
void read(int &ans) {
long long x = 0, w = 1;
char ch = 0;
while (!isdigit(ch)) {
if (ch == '-') w = -1;
ch = getchar();
}
while (isdigit(ch)) {
x = x * 10 + (ch - '0');
ch = getchar();
}
ans = x * w;
}
int v[N];
long long mi[N];
long long ma[N];
set<int> se;
struct node {
int d, f, t, c;
} a[N];
bool cmp(node x, node y) { return x.d < y.d; }
int main() {
memset((mi), (INF), sizeof(mi));
memset((ma), (INF), sizeof(ma));
long long ans = mi[0];
long long ans1 = mi[0];
int n, m, k, d, f, t, c;
int s1, e1, s2, e2;
s1 = e1 = s2 = e2 = 0;
int flag = 0;
read(n), read(m), read(k);
for (int i = 0; i < m; ++i) {
read(d), read(f), read(t), read(c);
a[i] = {d, f, t, c};
flag = max(flag, d);
}
sort(a, a + m, cmp);
long long sum = 0;
for (int i = 0; i < m; ++i) {
if (a[i].f == 0) continue;
if (se.size() && se.find(a[i].f) != se.end()) {
if (v[a[i].f] > a[i].c) {
sum = sum - v[a[i].f] + a[i].c;
v[a[i].f] = a[i].c;
}
} else {
se.insert(a[i].f);
v[a[i].f] = a[i].c;
sum += a[i].c;
}
if (se.size() == n) {
if (s1 == 0)
e1 = s1 = a[i].d;
else
e1 = a[i].d;
mi[a[i].d] = min(mi[a[i].d], sum);
}
}
se.clear();
sum = 0;
for (int i = m - 1; i >= 0; --i) {
if (a[i].t == 0) continue;
if (se.size() && se.find(a[i].t) != se.end()) {
if (v[a[i].t] > a[i].c) {
sum = sum - v[a[i].t] + a[i].c;
v[a[i].t] = a[i].c;
}
} else {
se.insert(a[i].t);
v[a[i].t] = a[i].c;
sum += a[i].c;
}
if (se.size() == n) {
if (e2 == 0)
s2 = e2 = a[i].d;
else
s2 = a[i].d;
ma[a[i].d] = min(ma[a[i].d], sum);
}
}
for (int i = e1; i <= flag; ++i) mi[i] = mi[e1];
for (int i = 1; i <= s2; ++i) ma[i] = ma[s2];
for (int i = s1 + 1; i <= e1; ++i) {
if (mi[i] > mi[i - 1]) mi[i] = mi[i - 1];
}
for (int i = e2; i > s2; --i) {
if (ma[i - 1] > ma[i]) ma[i - 1] = ma[i];
}
for (int i = s1; i <= flag; ++i) {
if (i + k + 1 <= flag) ans = min(ans, mi[i] + ma[i + k + 1]);
}
if (ans >= ans1)
puts("-1");
else
cout << ans << "\n";
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
long long int cons;
long long int check(long long int a) {
if (a >= cons || a <= -cons) a %= cons;
return a;
}
long long int check2(long long int a) {
if (a > 0) return a;
long long int b = a / cons;
a -= b * cons;
if (a < 0) a += cons;
return a;
}
long long int GCD(long long int a, long long int b) {
if (b == 0) return a;
return GCD(b, a % b);
}
long long int exp(long long int a, long long int n) {
if (n == 0) return 1;
if (n == 1) return check(a);
long long int b = exp(a, n / 2);
if (n % 2 == 0) return check(b * b);
return check(b * check(b * a));
}
vector<pair<long long int, long long int> > arrive[1000000 + 2],
depart[1000000 + 2];
vector<pair<long long int, long long int> > store_min[100000 + 1];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cons = 1e9 + 7;
int n, m, k;
cin >> n >> m >> k;
vector<long long int> arrive_min, depart_min;
vector<int> cur_ind;
cur_ind.resize(n + 1);
arrive_min.resize(n + 1);
depart_min.resize(n + 1);
for (int i = 1; i <= n; i++)
arrive_min[i] = -1, cur_ind[i] = 0, depart_min[i] = 0;
for (int i = 0; i < m; i++) {
int first, second, z, w;
cin >> first >> second >> z >> w;
if (second == 0) {
depart[first].push_back({z, w});
store_min[z].push_back({w, first});
} else {
arrive[first].push_back({second, w});
}
}
for (int i = 1; i <= n; i++) sort(store_min[i].begin(), store_min[i].end());
int l = 1, r = k;
int cur_counter = 0;
long long int cur_cost = 0;
long long int ans = -1;
bool flag = true;
while (flag && r <= 1e6 + 1) {
for (auto itr : depart[r]) {
if (arrive_min[itr.first] != -1) {
int len = store_min[itr.first].size();
while (cur_ind[itr.first] < len &&
(store_min[itr.first][cur_ind[itr.first]].second) <= r)
cur_ind[itr.first]++;
if (cur_ind[itr.first] == len) {
flag = false;
break;
} else {
cur_cost -= depart_min[itr.first];
depart_min[itr.first] =
store_min[itr.first][cur_ind[itr.first]].first;
cur_cost += depart_min[itr.first];
}
}
}
if (!flag) break;
if (cur_counter == n) {
if (ans == -1)
ans = cur_cost;
else
ans = min(ans, cur_cost);
}
for (auto itr : arrive[l]) {
if (arrive_min[itr.first] == -1) {
arrive_min[itr.first] = itr.second;
cur_counter++;
cur_cost += itr.second;
int len = store_min[itr.first].size();
while (cur_ind[itr.first] < len &&
(store_min[itr.first][cur_ind[itr.first]].second) <= r)
cur_ind[itr.first]++;
if (cur_ind[itr.first] == len) {
flag = false;
break;
} else {
cur_cost -= depart_min[itr.first];
depart_min[itr.first] =
store_min[itr.first][cur_ind[itr.first]].first;
cur_cost += depart_min[itr.first];
}
} else {
cur_cost -= arrive_min[itr.first];
arrive_min[itr.first] = min(arrive_min[itr.first], itr.second);
cur_cost += arrive_min[itr.first];
}
}
l++;
r++;
}
cout << ans << endl;
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
const int N = 1e5, M = 1e6;
const double EPS = 1e-9;
const int INF = 1e9;
const long long INFL = 1000000000000000LL;
int n, m, k;
int minCostFirst[N + 5];
int minCostLast[N + 5];
long long prefCost[N + 5];
long long suffCost[N + 5];
struct trip {
int d, f, t, c;
} ar[N + 5];
bool CF(const trip &a, const trip &b) {
if (a.d != b.d) return a.d < b.d;
if (a.t != b.t) return a.t < b.t;
if (a.f != b.f) return a.f < b.f;
return a.c < b.c;
}
int precomfirst() {
int sisa = n;
int idx = -1;
long long pref = 0;
for (int i = 0; i < m; ++i) {
if (ar[i].t == 0) {
if (minCostFirst[ar[i].f] == -1) {
minCostFirst[ar[i].f] = ar[i].c;
pref += ar[i].c;
sisa--;
} else {
if (ar[i].c < minCostFirst[ar[i].f]) {
pref += ar[i].c - minCostFirst[ar[i].f];
minCostFirst[ar[i].f] = ar[i].c;
}
}
}
if (sisa == 0 && idx == -1) {
idx = i;
}
prefCost[i] = pref;
}
return idx;
}
int precomlast() {
int sisa = n;
int idx = -1;
long long suff = 0;
for (int i = m - 1; i >= 0; --i) {
if (ar[i].f == 0) {
if (minCostLast[ar[i].t] == -1) {
minCostLast[ar[i].t] = ar[i].c;
suff += ar[i].c;
sisa--;
} else {
if (ar[i].c < minCostLast[ar[i].t]) {
suff += ar[i].c - minCostLast[ar[i].t];
minCostLast[ar[i].t] = ar[i].c;
}
}
}
if (sisa == 0 && idx == -1) {
idx = i;
}
suffCost[i] = suff;
}
return idx;
}
int search(int day) {
int l = 0;
int r = m - 1;
int ans = m;
while (l <= r) {
int piv = (l + r) >> 1;
if (ar[piv].d >= day) {
ans = piv;
r = piv - 1;
} else {
l = piv + 1;
}
}
return ans;
}
long long mintot = 0;
int main() {
scanf("%d%d%d", &n, &m, &k);
memset(minCostFirst, -1, sizeof minCostFirst);
memset(minCostLast, -1, sizeof minCostLast);
for (int i = 0; i < m; ++i)
scanf("%d%d%d%d", &ar[i].d, &ar[i].f, &ar[i].t, &ar[i].c);
sort(ar, ar + m, CF);
int minfirst = precomfirst();
int maxlast = precomlast();
if (minfirst == -1 || maxlast == -1 ||
ar[minfirst].d + k + 1 > ar[maxlast].d) {
puts("-1");
return 0;
}
long long minall = INFL;
for (int i = minfirst; i <= maxlast; ++i) {
int minidx = search(ar[i].d + k + 1);
if (minidx <= maxlast) {
minall = min(minall, prefCost[i] + suffCost[minidx]);
}
}
printf("%lld\n", minall);
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.Set;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.HashSet;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.Comparator;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Rustam Musin ([email protected])
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
int m = in.readInt();
int k = in.readInt();
Fly[] to0 = new Fly[m];
Fly[] from0 = new Fly[m];
int to0Size = 0, from0Size = 0;
for (int i = 0; i < m; i++) {
int day = in.readInt();
int from = in.readInt();
int to = in.readInt();
int cost = in.readInt();
Fly fly = new Fly(day, from, to, cost);
if (from == 0) {
from0[from0Size++] = fly;
} else {
to0[to0Size++] = fly;
}
}
Arrays.sort(from0, 0, from0Size, Comparator.comparingInt(f -> f.day));
Arrays.sort(to0, 0, to0Size, Comparator.comparingInt(f -> f.day));
if (from0Size < n || to0Size < n) {
out.print(-1);
return;
}
boolean[] possibleEndFrom0 = new boolean[from0Size + 1];
long[] minCostFrom0 = new long[from0Size + 1];
int[] lastCostFrom0 = new int[n + 1];
Set<Integer> active = new HashSet<>();
for (int i = from0Size - 1; i >= 0; i--) {
Fly f = from0[i];
minCostFrom0[i] = minCostFrom0[i + 1];
if (active.add(f.to) || lastCostFrom0[f.to] > f.cost) {
minCostFrom0[i] -= lastCostFrom0[f.to];
minCostFrom0[i] += f.cost;
lastCostFrom0[f.to] = f.cost;
}
possibleEndFrom0[i] = active.size() == n;
}
active.clear();
long curCostTo0 = 0;
long minCost = Long.MAX_VALUE;
int[] lastCostTo0 = new int[n + 1];
for (int i = 0, j = 0; i < to0Size; i++) {
Fly f = to0[i];
if (active.add(f.from) || f.cost < lastCostTo0[f.from]) {
curCostTo0 -= lastCostTo0[f.from];
curCostTo0 += f.cost;
lastCostTo0[f.from] = f.cost;
}
if (active.size() == n) {
while (possibleEndFrom0[j] && from0[j].day - f.day - 1 < k) {
j++;
}
if (!possibleEndFrom0[j]) {
break;
}
minCost = Math.min(minCost, curCostTo0 + minCostFrom0[j]);
}
}
if (minCost == Long.MAX_VALUE) {
minCost = -1;
}
out.print(minCost);
}
class Fly {
int day;
int from;
int to;
int cost;
Fly(int day, int from, int to, int cost) {
this.day = day;
this.from = from;
this.to = to;
this.cost = cost;
}
public String toString() {
return "Fly{" +
"day=" + day +
", from=" + from +
", to=" + to +
", cost=" + cost +
'}';
}
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void print(long i) {
writer.print(i);
}
public void print(int i) {
writer.print(i);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| JAVA |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Pradyumn Agrawal coderbond007 PLEASE!! PLEASE!! HACK MY SOLUTION!!
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public static final int DAYS = 1000000;
public static final long INFTY = 1000_000_000_000L;
public void solve(int testNumber, FastReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int[] d = new int[m];
int[] f = new int[m];
int[] t = new int[m];
int[] c = new int[m];
in.nextIntArrays(d, f, t, c);
MiscUtils.decreaseByOne(d, f, t);
int[] first = ArrayUtils.createArray(DAYS, -1);
int[] next = new int[m];
for (int i = 0; i < m; i++) {
if (t[i] == -1) {
next[i] = first[d[i]];
first[d[i]] = i;
}
}
long[] inbound = new long[DAYS];
long[] current = ArrayUtils.createArray(n, INFTY);
long result = INFTY * n;
for (int i = 0; i < DAYS; i++) {
for (int j = first[i]; j != -1; j = next[j]) {
if (c[j] < current[f[j]]) {
result -= current[f[j]];
current[f[j]] = c[j];
result += c[j];
}
}
inbound[i] = result;
}
ArrayUtils.fill(first, -1);
for (int i = 0; i < m; i++) {
if (f[i] == -1) {
next[i] = first[d[i]];
first[d[i]] = i;
}
}
ArrayUtils.fill(current, INFTY);
result = INFTY * n;
long[] outbound = new long[DAYS];
for (int i = DAYS - 1; i >= 0; i--) {
for (int j = first[i]; j != -1; j = next[j]) {
if (c[j] < current[t[j]]) {
result -= current[t[j]];
current[t[j]] = c[j];
result += c[j];
}
}
outbound[i] = result;
}
long answer = Long.MAX_VALUE;
for (int i = k + 1; i < DAYS; i++) {
answer = Math.min(answer, inbound[i - k - 1] + outbound[i]);
}
if (answer >= INFTY) {
answer = -1;
}
out.println(answer);
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int pnumChars;
private FastReader.SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
private int pread() {
if (pnumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= pnumChars) {
curChar = 0;
try {
pnumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (pnumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = pread();
while (isSpaceChar(c))
c = pread();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = pread();
}
int res = 0;
do {
if (c == ',') {
c = pread();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = pread();
} while (!isSpaceChar(c));
return res * sgn;
}
private boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
private static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public void nextIntArrays(int[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = nextInt();
}
}
}
private interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class ArrayUtils {
public static void fill(long[] array, long value) {
Arrays.fill(array, value);
}
public static void fill(int[] array, int value) {
Arrays.fill(array, value);
}
public static int[] createArray(int count, int value) {
int[] array = new int[count];
Arrays.fill(array, value);
return array;
}
public static long[] createArray(int count, long value) {
long[] array = new long[count];
Arrays.fill(array, value);
return array;
}
}
static class MiscUtils {
public static void decreaseByOne(int[]... arrays) {
for (int[] array : arrays) {
for (int i = 0; i < array.length; i++) {
array[i]--;
}
}
}
}
}
| JAVA |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
constexpr int MOD = 1000000007;
template <typename T, typename U>
std::istream& operator>>(std::istream& i, pair<T, U>& p) {
i >> p.first >> p.second;
return i;
}
template <typename T>
std::istream& operator>>(std::istream& i, vector<T>& t) {
for (auto& v : t) {
i >> v;
}
return i;
}
template <typename T>
std::ostream& operator<<(std::ostream& o, const vector<T>& t) {
for (size_t i = 0; i < t.size(); ++i) {
o << t[i] << " \n"[i == t.size() - 1];
}
return o;
}
template <typename T>
using minheap = priority_queue<T, vector<T>, greater<T>>;
template <typename T>
using maxheap = priority_queue<T, vector<T>, less<T>>;
auto fraclt = [](const std::pair<int, int>& a, const std::pair<int, int>& b) {
return (long long)a.first * b.second < (long long)b.first * a.second;
};
struct cmpfrac {
bool operator()(const std::pair<int, int>& a,
const std::pair<int, int>& b) const {
return (long long)a.first * b.second < (long long)b.first * a.second;
}
};
template <typename T>
bool in(T a, T b, T c) {
return a <= b && b < c;
}
unsigned int logceil(long long first) {
unsigned int b = 0;
while (first) {
first >>= 1;
++b;
}
return b;
}
namespace std {
template <typename T, typename U>
struct hash<pair<T, U>> {
hash<T> t;
hash<U> u;
size_t operator()(const pair<T, U>& p) const {
return t(p.first) ^ (u(p.second) << 7);
}
};
} // namespace std
template <typename T, typename F>
T bsh(T l, T h, const F& f) {
T r = -1, m;
while (l <= h) {
m = (l + h) / 2;
if (f(m)) {
l = m + 1;
r = m;
} else {
h = m - 1;
}
}
return r;
}
template <typename T, typename F>
T bsl(T l, T h, const F& f) {
T r = -1, m;
while (l <= h) {
m = (l + h) / 2;
if (f(m)) {
h = m - 1;
r = m;
} else {
l = m + 1;
}
}
return r;
}
template <typename T>
T gcd(T a, T b) {
if (a < b) swap(a, b);
return b ? gcd(b, a % b) : a;
}
template <typename T>
class vector2 : public vector<vector<T>> {
public:
vector2() {}
vector2(size_t a, size_t b, T t = T())
: vector<vector<T>>(a, vector<T>(b, t)) {}
};
template <typename T>
class vector3 : public vector<vector<vector<T>>> {
public:
vector3() {}
vector3(size_t a, size_t b, size_t c, T t = T())
: vector<vector<vector<T>>>(a, vector<vector<T>>(b, vector<T>(c, t))) {}
};
template <typename T>
struct bounded_priority_queue {
inline bounded_priority_queue(unsigned int X) : A(X), B(0) {}
inline void push(unsigned int L, T V) {
B = max(B, L);
A[L].push(V);
}
inline const T& top() const { return A[B].front(); }
inline void pop() {
A[B].pop();
while (B > 0 && A[B].empty()) --B;
}
inline bool empty() const { return A[B].empty(); }
inline void clear() {
B = 0;
for (auto& a : A) a = queue<T>();
}
private:
vector<queue<T>> A;
unsigned int B;
};
constexpr long long infty = 3e11;
constexpr int days = 1000000;
class TaskB {
public:
void solve(istream& cin, ostream& cout) {
int N, M, K;
cin >> N >> M >> K;
vector<vector<std::pair<int, int>>> I(days), O(days);
for (int i = 0; i < M; ++i) {
int d, f, t, c;
cin >> d >> f >> t >> c;
--d;
if (f == 0) {
O[d].emplace_back(t - 1, c);
} else {
I[d].emplace_back(f - 1, c);
}
}
vector<long long> TI(days), TO(days);
long long c = N * infty;
vector<long long> R(N, infty);
for (int i = 0; i < days; ++i) {
for (std::pair<int, int>& f : I[i]) {
c -= R[f.first];
R[f.first] = min(R[f.first], (long long)f.second);
c += R[f.first];
}
TI[i] = c;
}
c = N * infty;
R = vector<long long>(N, infty);
for (int i = days - 1; i >= 0; --i) {
for (std::pair<int, int>& f : O[i]) {
c -= R[f.first];
R[f.first] = min(R[f.first], (long long)f.second);
c += R[f.first];
}
TO[i] = c;
}
long long ans = 2 * N * infty;
for (int i = 0; i + K + 1 < days; ++i) {
ans = min(ans, TI[i] + TO[i + K + 1]);
}
if (ans < infty) {
cout << ans << endl;
} else {
cout << -1 << endl;
}
}
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
TaskB solver;
std::istream& in(std::cin);
std::ostream& out(std::cout);
solver.solve(in, out);
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
void write(long long x) {
if (x < 0) {
putchar('-');
x = -x;
}
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
long long read() {
long long d = 0, w = 1;
char c = getchar();
for (; c < '0' || c > '9'; c = getchar())
if (c == '-') w = -1;
for (; c >= '0' && c <= '9'; c = getchar()) d = (d << 1) + (d << 3) + c - 48;
return d * w;
}
void wln(long long x) {
write(x);
putchar('\n');
}
void wrs(long long x) {
write(x);
putchar(' ');
}
struct arr {
long long d, f, t, c;
};
arr a[1000010];
long long n, m, k, mi, ma, nn, f[1000010], mst[1000010], g[1000010],
vis[1000010], ans;
bool cmp(arr a, arr b) { return a.d < b.d; }
signed main() {
n = read();
m = read();
k = read();
if (!m) {
write(-1);
return 0;
}
mi = 100000000007;
for (long long i = 1; i <= m; i++) {
a[i].d = read();
mi = min(a[i].d, mi);
ma = max(a[i].d, ma);
a[i].f = read();
a[i].t = read();
a[i].c = read();
}
sort(a + 1, a + m + 1, cmp);
nn = n;
f[mi - 1] = 100000000007 * n;
for (long long i = 1; i <= n; mst[i++] = 100000000007)
;
for (long long i = mi, j = 1; i <= ma; i++)
for (f[i] = f[i - 1]; a[j].d == i; j++) {
if (a[j].t != 0) continue;
if (!vis[a[j].f]) {
nn--;
vis[a[j].f] = 1;
}
if (a[j].c < mst[a[j].f]) {
f[i] = f[i] - mst[a[j].f] + a[j].c;
mst[a[j].f] = a[j].c;
}
}
if (nn) {
write(-1);
return 0;
}
memset(vis, 0, sizeof vis);
nn = n;
g[ma + 1] = 100000000007 * n;
for (long long i = 1; i <= n; mst[i++] = 100000000007)
;
for (long long i = ma, j = m; i >= mi; i--)
for (g[i] = g[i + 1]; a[j].d == i; j--) {
if (a[j].f != 0) continue;
if (!vis[a[j].t]) {
nn--;
vis[a[j].t] = 1;
}
if (a[j].c < mst[a[j].t]) {
g[i] = g[i] - mst[a[j].t] + a[j].c;
mst[a[j].t] = a[j].c;
}
}
if (nn) {
write(-1);
return 0;
}
ans = 100000000007;
for (long long i = mi; i + k < ma; i++) ans = min(ans, f[i] + g[i + k + 1]);
write(ans >= 100000000007 ? -1 : ans);
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int n, m, k;
struct Flight {
int d, f, t, c;
bool operator<(const Flight &ot) const { return d < ot.d; }
} v[1000002];
int costJ[100002];
long long cost[1000002];
int firstV;
long long ans;
void getJury() {
cost[0] = 1LL * 1000000002 * n;
for (int i = 1; i <= n; ++i) costJ[i] = 1000000002;
int d = 1, cnt = n;
firstV = v[m].d + 1;
for (int i = 1; i <= m; ++i) {
int prv = costJ[v[i].t];
while (d <= v[i].d) {
cost[d] = cost[d - 1];
++d;
}
if (v[i].t) {
costJ[v[i].t] = min(costJ[v[i].t], v[i].c);
if (prv == 1000000002 && costJ[v[i].t] != 1000000002) {
--cnt;
if (!cnt) firstV = v[i].d;
}
}
if (v[i].t) cost[v[i].d] = cost[v[i].d] - prv + costJ[v[i].t];
}
for (int i = 2; i <= v[i].d; ++i) cost[i] = min(cost[i], cost[i - 1]);
}
void exitJury() {
ans = 1LL * n * 1000000002;
for (int i = 1; i <= n; ++i) costJ[i] = 1000000002;
long long sum = 1LL * 1000000002 * n;
int cnt = n;
for (int i = m; i >= 1; --i) {
int prv = costJ[v[i].f];
if (v[i].f) {
costJ[v[i].f] = min(costJ[v[i].f], v[i].c);
sum = sum + 1LL * costJ[v[i].f] - 1LL * prv;
if (prv == 1000000002 && costJ[v[i].f] != 1000000002) --cnt;
}
if (v[i].d <= k) return;
if (cnt == 0 && firstV <= (v[i].d - k - 1))
ans = min(ans, sum + cost[v[i].d - k - 1]);
}
}
int main() {
scanf("%d%d%d", &n, &m, &k);
for (int i = 1; i <= m; ++i)
scanf("%d%d%d%d", &v[i].d, &v[i].t, &v[i].f, &v[i].c);
sort(v + 1, v + m + 1);
getJury();
exitJury();
if (ans >= 1LL * 1000000002 * n)
printf("-1");
else
printf("%lld\n", ans);
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Rustam Musin ([email protected])
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
long[] minCostIn = new long[((int) 1e6 + 200)];
long[] minCostOut = new long[(int) 1e6 + 200];
long[] minCostPerson = new long[(int) 1e5 + 200];
Edge[] ways;
public void solve(int testNumber, InputReader in, OutputWriter out) {
Arrays.fill(minCostIn, Long.MAX_VALUE);
Arrays.fill(minCostOut, Long.MAX_VALUE);
Arrays.fill(minCostPerson, Long.MAX_VALUE);
int n = in.readInt(), m = in.readInt(), k = in.readInt();
ways = new Edge[m];
for (int i = 0; i < m; ++i) {
ways[i] = new Edge(in.readInt(), in.readInt(), in.readInt(), in.readInt());
}
Arrays.sort(ways, 0, m);
long answer = 0;
int available = 0;
for (int i = 0; i < m; i++) {
if (ways[i].from != 0) {
int person = ways[i].from;
if (minCostPerson[person] == Long.MAX_VALUE) {
available++;
} else {
answer -= minCostPerson[person];
}
minCostPerson[person] = Math.min(minCostPerson[person], ways[i].cost);
answer += minCostPerson[person];
if (available == n) {
minCostIn[ways[i].day + 1] = Math.min(minCostIn[ways[i].day + 1], answer);
}
}
}
Arrays.fill(minCostPerson, Long.MAX_VALUE);
available = 0;
answer = 0;
for (int i = m - 1; i >= 0; --i) {
if (ways[i].from == 0) {
int person = ways[i].t;
if (minCostPerson[person] == Long.MAX_VALUE) {
available++;
} else {
answer -= minCostPerson[person];
}
minCostPerson[person] = Math.min(minCostPerson[person], ways[i].cost);
answer += minCostPerson[person];
if (available == n) {
minCostOut[ways[i].day - 1] = Math.min(minCostOut[ways[i].day - 1], answer);
}
}
}
Tree tree = new Tree();
long minSum = Long.MAX_VALUE;
int max = (int) 1e6 + 1;
for (int day = 0; day < max - k; ++day) {
long leftSum = tree.get(1, 0, max - 1, 0, day, 0);
long rightSum = tree.get(1, 0, max - 1, day + k - 1, max - 1, 1);
if (leftSum != Long.MAX_VALUE && rightSum != Long.MAX_VALUE) {
minSum = Math.min(minSum, leftSum + rightSum);
}
}
if (minSum == Long.MAX_VALUE) {
minSum = -1;
}
out.print(minSum);
}
class Tree {
long[][] tree = new long[2][4 * ((int) 1e6 + 200)];
Tree() {
build(1, 0, ((int) 1e6 + 1) - 1);
}
void build(int v, int tl, int tr) {
if (tl == tr) {
tree[0][v] = minCostIn[tl];
tree[1][v] = minCostOut[tl];
} else {
int mid = (tl + tr) / 2;
build(v + v, tl, mid);
build(v + v + 1, mid + 1, tr);
for (int t = 0; t < 2; ++t) {
tree[t][v] = Math.min(tree[t][v + v], tree[t][v + v + 1]);
}
}
}
long get(int v, int tl, int tr, int l, int r, int type) {
if (l > r) {
return Long.MAX_VALUE;
}
if (l == tl && r == tr) {
return tree[type][v];
}
int mid = (tl + tr) / 2;
return Math.min(get(v + v, tl, mid, l, Math.min(r, mid), type),
get(v + v + 1, mid + 1, tr, Math.max(l, mid + 1), r, type));
}
}
class Edge implements Comparable<Edge> {
int day;
int from;
int t;
int cost;
public Edge(int day, int from, int to, int cost) {
this.day = day;
this.from = from;
this.t = to;
this.cost = cost;
}
public int compareTo(Edge o) {
int c = Integer.compare(day, o.day);
if (c == 0) {
c = Integer.compare(c, o.cost);
}
return c;
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void print(long i) {
writer.print(i);
}
}
}
| JAVA |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
struct item {
int d, f, t, c;
bool operator<(const item &o) const { return d < o.d; }
void read() { cin >> d >> f >> t >> c; }
};
void solve(int n) {
int m, k;
cin >> m >> k;
vector<item> v(m);
for (int i = 0; i < (int)(m); ++i) v[i].read();
sort((v).begin(), (v).end());
int D = 0;
for (int i = 0; i < (int)(m); ++i) D = max(v[i].d + 2, D);
const long long inf = (long long)1e18;
vector<long long> pref(D, inf), suff(D, inf);
{
vector<long long> mcost(n, inf);
int ptr = m - 1;
int cnt = n;
for (int i = ((int)(D)-1); i >= 0; --i) {
suff[i] = (i + 1 == D ? inf : suff[i + 1]);
while (ptr >= 0 && v[ptr].d == i) {
if (v[ptr].f == 0) {
int to = v[ptr].t - 1;
if (mcost[to] > v[ptr].c) {
if (mcost[to] == inf) {
cnt--;
mcost[to] = v[ptr].c;
if (cnt == 0)
suff[i] = accumulate((mcost).begin(), (mcost).end(), 0LL);
} else if (cnt == 0) {
suff[i] -= mcost[to];
mcost[to] = v[ptr].c;
suff[i] += mcost[to];
} else
mcost[to] = v[ptr].c;
}
}
ptr--;
}
}
}
{
vector<long long> mcost(n, inf);
int ptr = 0;
int cnt = n;
for (int i = 0; i < (int)(D); ++i) {
pref[i] = (i == 0 ? inf : pref[i - 1]);
while (ptr < (int)(v).size() && v[ptr].d == i) {
if (v[ptr].t == 0) {
int to = v[ptr].f - 1;
if (mcost[to] > v[ptr].c) {
if (mcost[to] == inf) {
cnt--;
mcost[to] = v[ptr].c;
if (cnt == 0)
pref[i] = accumulate((mcost).begin(), (mcost).end(), 0LL);
} else if (cnt == 0) {
pref[i] -= mcost[to];
mcost[to] = v[ptr].c;
pref[i] += mcost[to];
} else
mcost[to] = v[ptr].c;
}
}
ptr++;
}
}
}
long long ans = inf;
for (int i = 0; i < (int)(D); ++i)
if (0 < i && i + k < D) ans = min(ans, pref[i - 1] + suff[i + k]);
cout << (ans == inf ? -1 : ans) << endl;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n;
while (cin >> n) solve(n);
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | /*
* DA-IICT
* Author: Jugal Kalal
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class Codeforces{
static long mod=(long)Math.pow(10,9)+7l;
public static void main(String args[]){
new Thread(null, new Runnable() {
public void run() {
try{
solve();
w.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}, "1", 1 << 26).start();
}
static InputReader in;
static PrintWriter w;
static void solve(){
in = new InputReader(System.in);
w = new PrintWriter(System.out);
int n=in.nextInt();
int m=in.nextInt();
int k=in.nextInt();
int size=1000005;
HashSet<Triple> sets[]=new HashSet[size];
for(int i=0;i<size;i++) {
sets[i]=new HashSet<>();
}
while(m-->0) {
int day=in.nextInt();
int dcity=in.nextInt();
int acity=in.nextInt();
long cost=in.nextLong();
Triple t=new Triple(dcity==0?true:false,dcity==0?acity:dcity,cost);
sets[day].add(t);
}
long prefix[]=new long[size];
long suffix[]=new long[size];
Arrays.fill(prefix,Integer.MAX_VALUE);
Arrays.fill(suffix,Integer.MAX_VALUE);
long total=0;
HashMap<Integer,Long> map=new HashMap<>();
for(int i=0;i<size;i++) {
for(Triple t:sets[i]) {
if(!t.flag) {
if(map.containsKey(t.city)) {
if(map.get(t.city)>t.cost) {
total+=t.cost-map.get(t.city);
map.put(t.city,t.cost);
}
}else {
total+=t.cost;
map.put(t.city,t.cost);
}
}
}
if(map.size()>=n) {
prefix[i]=total;
}
}
map=new HashMap<>();
total=0;
for(int i=size-1;i>=0;i--) {
for(Triple t:sets[i]) {
if(t.flag) {
if(map.containsKey(t.city)) {
if(map.get(t.city)>t.cost) {
total-=map.get(t.city);
total+=t.cost;
map.put(t.city,t.cost);
}
}else {
total+=t.cost;
map.put(t.city,t.cost);
}
}
}
if(map.size()>=n) {
suffix[i]=total;
}
}
long ans=Long.MAX_VALUE;
for(int i=0;i<size;i++) {
if(prefix[i]!=Integer.MAX_VALUE&&(i+1+k)<size&&suffix[i+1+k]!=Integer.MAX_VALUE) {
ans=Math.min(ans,prefix[i]+suffix[i+1+k]);
}
}
if(ans==Long.MAX_VALUE) {
w.println("-1");
}else {
w.println(ans);
}
}
static class Triple{
boolean flag=false;
int city;
long cost;
public Triple(boolean flag,int city,long cost) {
this.flag=flag;
this.city=city;
this.cost=cost;
}
}
static ArrayList<Integer> adj[]; //Adjacency Lists
static int V; // No. of vertices
// Constructor
static void Graph(int v){
V = v;
adj = new ArrayList[v];
for (int i=0; i<v; ++i){
adj[i] = new ArrayList();
}
}
// Function to add an edge into the graph
static void addEdge(int u,int v){
adj[u].add(v);
adj[v].add(u);
}
static HashSet<Integer> set=new HashSet<>();
static void sieve(int N){
boolean isPrime[]=new boolean[N+1];
isPrime[0] = true;
isPrime[1] = true;
for(int i = 2; i * i <= N; ++i) {
if(isPrime[i] == false) {//Mark all the multiples of i as composite numbers
for(int j = i * i; j <= N ;j += i)
isPrime[j] = true;
}
}
for(int i=0;i<=N;i++) {
if(!isPrime[i]) {
set.add(i);
}
}
}
static int Arr[];
static long size[];
//modified initialize function:
static void initialize(int N){
Arr=new int[N];
size=new long[N];
for(int i = 0;i<N;i++){
Arr[ i ] = i ;
size[ i ] = 1;
}
}
static boolean find(int A,int B){
if( root(A)==root(B) )//if A and B have same root,means they are connected.
return true;
else
return false;
}
// modified root function.
static void weighted_union(int A,int B){
int root_A = root(A);
int root_B = root(B);
if(size[root_A] < size[root_B ]){
Arr[ root_A ] = Arr[root_B];
size[root_B] += size[root_A];
}
else{
Arr[ root_B ] = Arr[root_A];
size[root_A] += size[root_B];
}
}
static int root (int i){
while(Arr[ i ] != i){
Arr[ i ] = Arr[ Arr[ i ] ] ;
i = Arr[ i ];
}
return i;
}
// static long[] isHamiltonian_path(int n){
// boolean dp[][]=new boolean[n][1<<n];
// long ans[]=new long[n];
// long sum[]=new long[n];
// for(int i=0;i<n;i++){
// dp[i][1<<i]=true;
// ans[i]=0;
// sum[i]=i+1;
// }
// for(int mask=0;mask<(1<<n);mask++){
// int s=0;
// int count=0,temp=mask;
// while(temp>0){
// s+=1+Math.log(temp&(-temp))/Math.log(2);
// temp=temp&(temp-1);
// count++;
// }
// for(int j=0;j<n;j++){
// if((mask&(1<<j))>0){
// for(int k=0;k<n;k++){
// if(j!=k&&(mask&(1<<k))>0&&adj[j][k]&&dp[k][mask^(1<<j)]){
// dp[j][mask]=true;
// ans[j]=Math.max(ans[j],count-1);
// if(ans[j]==count-1){
// sum[j]=Math.max(sum[j], s);
// }
// }
// }
// }
// }
// }
// return sum;
// }
static long gcd(long a,long b){
if(a==0){
return b;
}
return gcd(b%a,a);
}
static long power(long base, long exponent, long modulus){
long result = 1L;
while (exponent > 0) {
if (exponent % 2L == 1L)
result = (result * base) % modulus;
exponent = exponent >> 1;
base = (base * base) % modulus;
}
return result;
}
static HashMap<Long,Long> primeFactors(long n){
HashMap<Long,Long> ans=new HashMap<Long,Long>();
// Print the number of 2s that divide n
while (n%2L==0L)
{
if(ans.containsKey(2L)){
ans.put(2L,ans.get(2L)+1L);
}else{
ans.put(2L,1L);
}
n /= 2L;
}
// n must be odd at this point. So we can
// skip one element (Note i = i +2)
for (long i = 3; i <= Math.sqrt(n); i+= 2L)
{
// While i divides n, print i and divide n
while (n%i == 0)
{
if(ans.containsKey(i)){
ans.put(i,ans.get(i)+1L);
}else{
ans.put(i,1L);
}
n /= i;
}
}
// This condition is to handle the case whien
// n is a prime number greater than 2
if (n > 2)
ans.put(n,1L);
return ans;
}
////for marking all prime numbers greater than 1 and less than equal to N
// //if str2 (pattern) is subsequence of str1 (Text) or not
// static boolean function(String str1,String str2){
// str2 = str2.replace("", ".*"); //returns .*a.*n.*n.*a.
// return (str1.matches(str2)); // returns true
// }
static boolean isPrime(long n){
if(n < 2L) return false;
if(n == 2L || n == 3L) return true;
if(n%2L == 0 || n%3L == 0) return false;
long sqrtN = (long)Math.sqrt(n)+1L;
for(long i = 6L; i <= sqrtN; i += 6L) {
if(n%(i-1) == 0 || n%(i+1) == 0) return false;
}
return true;
}
// static HashMap<Integer,Integer> level;;
// static HashMap<Integer,Integer> parent;
// static boolean T[][][];
// static void subsetSum(int input[], int total, int count) {
// T = new boolean[input.length + 1][total + 1][count+1];
// for (int i = 0; i <= input.length; i++) {
// T[i][0][0] = true;
// for(int j = 1; j<=count; j++){
// T[i][0][j] = false;
// }
// }
// int sum[]=new int[input.length+1];
// for(int i=1;i<=input.length;i++){
// sum[i]=sum[i-1]+input[i-1];
// }
// for (int i = 1; i <= input.length; i++) {
// for (int j = 1; j <= (int)Math.min(total,sum[i]); j++) {
// for (int k = 1; k <= (int)Math.min(i,count); k++){
// if (j >= input[i - 1]) {//Exclude and Include
// T[i][j][k] = T[i - 1][j][k] || T[i - 1][j - input[i - 1]][k-1];
// } else {
// T[i][j][k] = T[i-1][j][k];
// }
// }
// }
// }
// }
// static <K,V extends Comparable<? super V>>
// SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map){
// SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
// new Comparator<Map.Entry<K,V>>() {
// @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
// int res = e2.getValue().compareTo(e1.getValue());
// return res != 0 ? res : 1;
// }
// }
// );
// sortedEntries.addAll(map.entrySet());
// return sortedEntries;
// }
//minimum prime factor of all the numbers less than n
static int minPrime[];
static void minimumPrime(int n){
minPrime=new int[n+1];
minPrime[1]=1;
for (int i = 2; i * i <= n; ++i) {
if (minPrime[i] == 0) { //If i is prime
for (int j = i * i; j <= n; j += i) {
if (minPrime[j] == 0) {
minPrime[j] = i;
}
}
}
}
for (int i = 2; i <= n; ++i) {
if (minPrime[i] == 0) {
minPrime[i] = i;
}
}
}
static long modInverse(long A, long M){
long x=extendedEuclid(A,M)[0];
return (x%M+M)%M; //x may be negative
}
static long[] extendedEuclid(long A, long B){
if(B == 0) {
long d = A;
long x = 1;
long y = 0;
return new long[]{x,y,d};
}
else {
long arr[]=extendedEuclid(B, A%B);
long temp = arr[0];
arr[0] = arr[1];
arr[1] = temp - (A/B)*arr[1];
return arr;
}
}
static class InputReader{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream){
this.stream = stream;
}
public int read(){
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public String nextLine(){
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String readString(){
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong(){
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt(){
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n){
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n){
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
public boolean isSpaceChar(int c){
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c){
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter{
public boolean isSpaceChar(int ch);
}
}
} | JAVA |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | import java.io.*;
import java.util.*;
import java.util.Map.Entry;
public class Main {
static InputReader in = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
static long oo = (long)1e12;
public static void main(String[] args) {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
F[] f = new F[m];
for(int i=0; i<m; ++i) {
int day = in.nextInt();
int from = in.nextInt();
int to = in.nextInt();
int cost = in.nextInt();
f[i] = new F(day, from, to, cost);
}
Arrays.sort(f);
int[] a = new int[n+1];
HashMap<Integer, Long> acost = new HashMap<>();
long total = 0;
int arCnt = 0;
for(int i=0; i<m; ++i) {
F curr = f[i];
if(curr.from == 0)
continue;
if(a[curr.from] == 0) {
total += curr.cost;
a[curr.from] = curr.cost;
arCnt++;
}
else if(curr.cost < a[curr.from]) {
total -= a[curr.from];
total += curr.cost;
a[curr.from] = curr.cost;
}
if(arCnt == n)
acost.put(curr.day, total);
}
int[] b = new int[n+1];
TreeMap<Integer, Long> bcost = new TreeMap<>();
total = 0;
int lvCnt = 0;
for(int i=m-1; i >= 0; --i) {
F curr = f[i];
if(curr.to == 0)
continue;
if(b[curr.to] == 0) {
total += curr.cost;
b[curr.to] = curr.cost;
lvCnt++;
}
else if(curr.cost < b[curr.to]) {
total -= b[curr.to];
total += curr.cost;
b[curr.to] = curr.cost;
}
if(lvCnt == n)
bcost.put(curr.day, total);
}
long min = oo;
Set<Integer> ks = acost.keySet();
for(int d : ks) {
long cst = acost.get(d);
int dd = d + k + 1;
Entry<Integer, Long> ceil = bcost.ceilingEntry(dd);
if(ceil != null) {
cst += ceil.getValue();
min = Math.min(min, cst);
}
}
if(min == oo)
min = -1;
System.out.println(min);
out.close();
}
static class F implements Comparable<F> {
int day, from, to, cost;
public F(int day, int from, int to, int cost) {
super();
this.day = day;
this.from = from;
this.to = to;
this.cost = cost;
}
@Override
public int compareTo(F o) {
// TODO Auto-generated method stub
return day - o.day;
}
}
}
class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
} | JAVA |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int n, m, k;
int d[100005];
int f[100005];
int t[100005];
int c[100005];
long long to[1000005], from[1000005];
long long cost[100005];
int main() {
cin >> n >> m >> k;
for (int i = (int)(0); i < (int)(m); ++i) cin >> d[i] >> f[i] >> t[i] >> c[i];
{
for (int i = (int)(1); i < (int)(n + 1); ++i)
cost[i] = 1e12, to[0] += cost[i];
set<pair<int, int> > Sp;
for (int i = (int)(0); i < (int)(m); ++i) Sp.insert({d[i], i});
for (auto p : Sp) {
int i = p.second;
if (f[i] == 0) continue;
if (c[i] > cost[f[i]]) continue;
to[d[i]] -= cost[f[i]] - c[i];
cost[f[i]] = c[i];
}
for (int i = (int)(0); i < (int)(1000001); ++i) to[i + 1] += to[i];
}
{
for (int i = (int)(1); i < (int)(n + 1); ++i)
cost[i] = 1e12, from[1000001] += cost[i];
set<pair<int, int> > Sp;
for (int i = (int)(0); i < (int)(m); ++i) Sp.insert({-d[i], i});
for (auto p : Sp) {
int i = p.second;
if (t[i] == 0) continue;
if (c[i] > cost[t[i]]) continue;
from[d[i]] -= cost[t[i]] - c[i];
cost[t[i]] = c[i];
}
for (int i = 1000000; i >= 0; --i) from[i] += from[i + 1];
}
long long sol = 1e12;
for (int i = (int)(0); i < (int)(1000001); ++i) {
int j = i + k + 1;
if (j > 1000001) break;
sol = min(sol, to[i] + from[j]);
}
if (sol == 1e12)
cout << -1 << endl;
else
cout << sol << endl;
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
/**
* @author Don Li
*/
public class JuryMeeting {
int N = (int) 1e6 + 10;
int INF = (int) 1e9;
void solve() {
int n = in.nextInt(), m = in.nextInt(), k = in.nextInt();
int[] d = new int[m], f = new int[m], t = new int[m], c = new int[m];
for (int i = 0; i < m; i++) {
d[i] = in.nextInt();
f[i] = in.nextInt();
t[i] = in.nextInt();
c[i] = in.nextInt();
}
Queue<Integer> arrive = new PriorityQueue<>(Comparator.comparingInt(i -> d[i]));
Queue<Integer> leave = new PriorityQueue<>(Comparator.comparingInt(i -> -d[i]));
for (int i = 0; i < m; i++) {
if (f[i] > 0) arrive.offer(i);
else leave.offer(i);
}
int[] cnt = new int[N], min = new int[n + 1];
long[] sum = new long[N];
Arrays.fill(min, INF);
for (int i = 1; i < N; i++) {
cnt[i] += cnt[i - 1];
sum[i] += sum[i - 1];
while (!arrive.isEmpty() && d[arrive.peek()] == i) {
int x = arrive.poll();
int city = f[x], cost = c[x];
if (min[city] == INF) {
cnt[i]++;
sum[i] += cost;
min[city] = cost;
} else if (min[city] > cost) {
sum[i] -= min[city] - cost;
min[city] = cost;
}
}
}
long ans = Long.MAX_VALUE;
int[] cnt2 = new int[N], min2 = new int[n + 1];
long[] sum2 = new long[N];
Arrays.fill(min2, INF);
for (int i = N - 2; i > 0; i--) {
cnt2[i] += cnt2[i + 1];
sum2[i] += sum2[i + 1];
while (!leave.isEmpty() && d[leave.peek()] == i) {
int x = leave.poll();
int city = t[x], cost = c[x];
if (min2[city] == INF) {
cnt2[i]++;
sum2[i] += cost;
min2[city] = cost;
} else if (min2[city] > cost) {
sum2[i] -= min2[city] - cost;
min2[city] = cost;
}
if (i - k - 1 >= 0 && cnt[i - k - 1] == n && cnt2[i] == n) {
ans = Math.min(ans, sum[i - k - 1] + sum2[i]);
}
}
}
if (ans == Long.MAX_VALUE) ans = -1;
out.println(ans);
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new JuryMeeting().solve();
out.close();
}
static FastScanner in;
static PrintWriter out;
static class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
| JAVA |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
int n, m, k;
int d1[100010], f1[100010], t1[100010], c1[100010];
int d2[100010], f2[100010], t2[100010], c2[100010];
int idx[100010];
long long cs1[1000010], cs2[1000010];
int vis[100010], num;
int m1, m2;
int cost1[100010];
int sign1[1000010];
int cost2[100010];
int sign2[1000010];
long long res;
int mk1, mk2;
int s1, s2;
int d3[100010], f3[100010], t3[100010], c3[100010];
int cmp(const void *aa, const void *bb) {
int i1 = *((int *)aa);
int i2 = *((int *)bb);
return d1[i1] - d1[i2];
}
int cmp2(const void *aa, const void *bb) {
int i1 = *((int *)aa);
int i2 = *((int *)bb);
return d2[i2] - d2[i1];
}
void solve() {
int i, j;
s1 = 1000000000;
s2 = -1;
for (i = 0; i < m1; i++) idx[i] = i;
qsort(idx, m1, sizeof(int), cmp);
num = 0;
j = 0;
int ff;
mk1 = 0;
for (i = 0; i < m1; i++) {
if (mk1 < d1[i]) mk1 = d1[i];
}
for (i = 0; i <= mk1; i++) {
cs1[i + 1] = cs1[i];
if (sign1[i] == 1) sign1[i + 1] = 1;
while (j < m1 && d1[idx[j]] <= i) {
ff = f1[idx[j]];
if (vis[ff] == 0) {
num++;
vis[ff] = 1;
cs1[i + 1] += c1[idx[j]];
cost1[ff] = c1[idx[j]];
if (num == n) {
sign1[i + 1] = 1;
s1 = i + 1;
}
} else {
if (cost1[ff] > c1[idx[j]]) {
cs1[i + 1] += c1[idx[j]] - cost1[ff];
cost1[ff] = c1[idx[j]];
}
if (num == n) sign1[i + 1] = 1;
}
j++;
}
}
for (i = 0; i < m2; i++) idx[i] = i;
qsort(idx, m2, sizeof(int), cmp2);
for (i = 0; i <= n; i++) vis[i] = 0;
num = 0;
j = 0;
int tt;
mk2 = 0;
for (i = 0; i < m2; i++) {
if (mk2 < d2[i]) mk2 = d2[i];
}
for (i = mk2; i > 0; i--) {
cs2[i - 1] = cs2[i];
if (sign2[i] == 1) sign2[i - 1] = 1;
while (j < m2 && d2[idx[j]] >= i) {
tt = t2[idx[j]];
if (vis[tt] == 0) {
num++;
vis[tt] = 1;
cs2[i - 1] += c2[idx[j]];
cost2[tt] = c2[idx[j]];
if (num == n) {
sign2[i - 1] = 1;
s2 = i - 1;
}
} else {
if (cost2[tt] > c2[idx[j]]) {
cs2[i - 1] += c2[idx[j]] - cost2[tt];
cost2[tt] = c2[idx[j]];
}
if (num == n) sign2[i - 1] = 1;
}
j++;
}
}
for (i = mk1 + 2; i <= mk2 + 1; i++) cs1[i] = cs1[i - 1];
res = -1;
for (i = 0; i <= mk1 + 1; i++) {
if ((i >= s1 && i + k - 1 <= mk2 && i + k - 1 <= s2) &&
(res == -1 || res > cs1[i] + cs2[i + k - 1]))
res = cs1[i] + cs2[i + k - 1];
}
for (i = mk2; i > 0; i--) {
if ((i - k + 1 >= 0 && i - k + 1 >= s1 && i <= s2) &&
(res == -1 || res > cs1[i - k + 1] + cs2[i]))
res = cs1[i - k + 1] + cs2[i];
}
printf("%I64d\n", res);
}
int main() {
int i;
scanf("%d%d%d", &n, &m, &k);
int dd, ff, tt, cc;
m1 = m2 = 0;
for (i = 0; i < m; i++) {
scanf("%d%d%d%d", &dd, &ff, &tt, &cc);
d3[i] = dd;
f3[i] = ff;
t3[i] = tt;
c3[i] = cc;
if (tt == 0) {
d1[m1] = dd;
f1[m1] = ff;
t1[m1] = tt;
c1[m1] = cc;
m1++;
} else {
d2[m2] = dd;
f2[m2] = ff;
t2[m2] = tt;
c2[m2] = cc;
m2++;
}
}
solve();
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
public class Template {
long MODULO = 1L * 1000 * 1000 * 1000 * 1000 * 1000 ;
long b = 31;
String fileName = "";
class Point{
int x, y;
Point(int x, int y){
this.x = x;
this.y = y;
}
}
class Flight implements Comparable<Flight>{
int from, to, cost, day;
Flight(int day, int from, int to, int cost){
this.from = from;
this.cost = cost;
this.day = day;
this.to = to;
}
@Override
public int compareTo(Flight o) {
return Integer.compare(this.day, o.day);
}
}
void solve() throws IOException {
int n = readInt();
int m = readInt();
int k = readInt();
Flight[] flights = new Flight[m];
for(int i=0; i<m; ++i){
flights[i] = new Flight(readInt(), readInt()-1, readInt()-1, readInt());
}
Arrays.sort(flights);
int countZeroTo = n;
int[] curMinTo = new int[n];
long[] prefMinTo = new long[2000*1000];
boolean[] canPrefTo = new boolean[2000*1000];
long curSumTo = 0;
int countZeroFrom = n;
int[] curMinFrom = new int[n];
long[] prefMinFrom = new long[2000*1000];
boolean[] canPrefFrom = new boolean[2000*1000];
long curSumFrom = 0;
for(int i=0; i<m; ++i){
if(flights[i].to < flights[i].from){
if(curMinTo[flights[i].from] == 0){
countZeroTo--;
curMinTo[flights[i].from] = flights[i].cost;
curSumTo += flights[i].cost;
}else{
if(curMinTo[flights[i].from] > flights[i].cost){
curSumTo -= curMinTo[flights[i].from];
curSumTo += flights[i].cost;
curMinTo[flights[i].from] = flights[i].cost;
}
}
canPrefTo[flights[i].day + 1] = countZeroTo == 0;
prefMinTo[flights[i].day] = curSumTo;
}
}
for(int i=m-1; i>=0; --i){
if(flights[i].to > flights[i].from){
if(curMinFrom[flights[i].to] == 0){
countZeroFrom--;
curMinFrom[flights[i].to] = flights[i].cost;
curSumFrom += flights[i].cost;
}else{
if(curMinFrom[flights[i].to] > flights[i].cost){
curSumFrom -= curMinFrom[flights[i].to];
curSumFrom += flights[i].cost;
curMinFrom[flights[i].to] = flights[i].cost;
}
}
canPrefFrom[flights[i].day] = countZeroFrom == 0;
prefMinFrom[flights[i].day] = curSumFrom;
}
}
long curTo = 0;
long curFrom = 0;
for(int i=1; i<2000000; ++i){
if(prefMinTo[i] == 0){
prefMinTo[i] = curTo;
}else{
curTo = prefMinTo[i];
}
canPrefTo[i] |= canPrefTo[i-1];
}
for(int i=2000000-2; i>=0; --i){
if(prefMinFrom[i] == 0){
prefMinFrom[i] = curFrom;
}else{
curFrom = prefMinFrom[i];
}
canPrefFrom[i] |= canPrefFrom[i+1];
}
for(int i=0; i<=15; ++i){
//out.println(prefMinTo[i] + " " +prefMinFrom[i]+ " " + canPrefTo[i] + " " + canPrefFrom[i]);
}
long ans = Long.MAX_VALUE;
for(int i=0; i<2000000 - 1; ++i){
if(i - k + 1 < 0 || !canPrefTo[i - k + 1] || !canPrefFrom[i + 1]){
continue;
}
ans = Math.min(prefMinTo[i - k] + prefMinFrom[i+1], ans);
}
out.println(ans == Long.MAX_VALUE ? -1:ans);
}
class Dsu{
int[] parent;
int countSets;
Dsu(int n){
countSets = n;
parent = new int[n];
for(int i=0; i<n; ++i){
parent[i] = i;
}
}
int findSet(int a){
if(parent[a] == a) return a;
parent[a] = findSet(parent[a]);
return parent[a];
}
void unionSets(int a, int b){
a = findSet(a);
b = findSet(b);
if(a!=b){
countSets--;
parent[a] = b;
}
}
}
int checkBit(int mask, int bit) {
return (mask >> bit) & 1;
}
boolean isLower(char c){
return c >= 'a' && c <= 'z';
}
////////////////////////////////////////////////////////////
class Pair implements Comparable<Pair>{
int ind,val;
Pair(int a, int b){
this.ind = a;
this.val = b;
}
@Override
public int compareTo(Pair o) {
return this.val - o.val;
}
}
class SegmentTree{
int[] t;
int n;
SegmentTree(int n){
t = new int[4*n];
build(new int[n+1], 1, 1, n);
}
void build (int a[], int v, int tl, int tr) {
if (tl == tr)
t[v] = a[tl];
else {
int tm = (tl + tr) / 2;
build (a, v*2, tl, tm);
build (a, v*2+1, tm+1, tr);
}
}
void update (int v, int tl, int tr, int l, int r, int add) {
if (l > r)
return;
if (l == tl && tr == r)
t[v] += add;
else {
int tm = (tl + tr) / 2;
update (v*2, tl, tm, l, Math.min(r,tm), add);
update (v*2+1, tm+1, tr, Math.max(l,tm+1), r, add);
}
}
int get (int v, int tl, int tr, int pos) {
if (tl == tr)
return t[v];
int tm = (tl + tr) / 2;
if (pos <= tm)
return t[v] + get (v*2, tl, tm, pos);
else
return t[v] + get (v*2+1, tm+1, tr, pos);
}
}
class Fenwik {
long[] t;
int length;
Fenwik(int[] a) {
length = a.length + 100;
t = new long[length];
for (int i = 0; i < a.length; ++i) {
inc(i, a[i]);
}
}
void inc(int ind, int delta) {
for (; ind < length; ind = ind | (ind + 1)) {
t[ind] += delta;
}
}
long getSum(int r) {
long sum = 0;
for (; r >= 0; r = (r & (r + 1)) - 1) {
sum += t[r];
}
return sum;
}
}
int gcd(int a, int b){
return b == 0 ? a : gcd(b, a%b);
}
long binPow(long a, long b, long m) {
if (b == 0) {
return 1;
}
if (b % 2 == 1) {
return ((a % m) * (binPow(a, b - 1, m) % m)) % m;
} else {
long c = binPow(a, b / 2, m);
return (c * c) % m;
}
}
int minInt(int... values) {
int min = Integer.MAX_VALUE;
for (int value : values) min = Math.min(min, value);
return min;
}
int maxInt(int... values) {
int max = Integer.MIN_VALUE;
for (int value : values) max = Math.max(max, value);
return max;
}
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
new Template().run();
}
void run() throws NumberFormatException, IOException {
solve();
out.close();
};
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
String delim = " ";
Random rnd = new Random();
Template() throws FileNotFoundException {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} catch (Exception e) {
if (fileName.isEmpty()) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader(fileName + ".in"));
out = new PrintWriter(fileName + ".out");
}
}
tok = new StringTokenizer("");
}
String readLine() throws IOException {
return in.readLine();
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
String nextLine = readLine();
if (null == nextLine) {
return null;
}
tok = new StringTokenizer(nextLine);
}
return tok.nextToken();
}
int readInt() throws NumberFormatException, IOException {
return Integer.parseInt(readString());
}
byte readByte() throws NumberFormatException, IOException {
return Byte.parseByte(readString());
}
int[] readIntArray (int n) throws NumberFormatException, IOException {
int[] a = new int[n];
for(int i=0; i<n; ++i){
a[i] = readInt();
}
return a;
}
long readLong() throws NumberFormatException, IOException {
return Long.parseLong(readString());
}
double readDouble() throws NumberFormatException, IOException {
return Double.parseDouble(readString());
}
} | JAVA |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const double pi = acos(-1.0);
const int inf = 1e9;
const int maxn = 2e6 + 5;
void read(long long &x) {
char ch;
bool flag = 0;
for (ch = getchar(); !isdigit(ch) && ((flag |= (ch == '-')) || 1);
ch = getchar())
;
for (x = 0; isdigit(ch); x = (x << 1) + (x << 3) + ch - 48, ch = getchar())
;
x *= 1 - 2 * flag;
}
long long n, m, k;
struct inof {
long long d, f, t, c;
} p[maxn];
bool cmp(inof a, inof b) { return a.d < b.d; }
long long res[maxn], tmp[maxn];
map<long long, long long> mp, mp1;
int main() {
cin >> n >> m >> k;
long long maxsize = 0;
for (int i = 0; i < m; i++) {
cin >> p[i].d >> p[i].f >> p[i].t >> p[i].c;
maxsize = max(maxsize, p[i].d);
}
for (int i = 1; i <= maxsize + 50; i++) res[i] = 1e12, tmp[i] = 1e12;
sort(p, p + m, cmp);
long long siz = 0, ans = 0;
for (int i = 0; i < m; i++) {
if (p[i].f) {
if (mp[p[i].f] == 0) {
siz++;
mp[p[i].f] = p[i].c;
ans += p[i].c;
} else {
if (mp[p[i].f] > p[i].c)
ans = ans + p[i].c - mp[p[i].f], mp[p[i].f] = p[i].c;
}
if (siz == n) {
res[p[i].d] = ans;
}
}
}
siz = 0;
ans = 0;
for (int i = m - 1; i >= 0; i--) {
if (p[i].t) {
if (mp1[p[i].t] == 0) {
siz++;
ans += p[i].c;
mp1[p[i].t] = p[i].c;
} else {
if (mp1[p[i].t] > p[i].c)
ans = ans + p[i].c - mp1[p[i].t], mp1[p[i].t] = p[i].c;
}
if (siz == n) {
tmp[p[i].d] = ans;
}
}
}
long long temp = tmp[maxsize + 5];
for (int i = maxsize + 5; i >= 0; i--) {
temp = min(temp, tmp[i]);
tmp[i] = temp;
}
temp = res[1];
ans = 1e12;
for (int i = 1; i <= maxsize - k; i++) {
temp = min(temp, res[i]);
ans = min(ans, temp + tmp[i + k + 1]);
}
if (ans >= 1e12) ans = -1;
cout << ans;
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | /**
* DA-IICT
* Author : Savaliya Sagar
*/
import java.io.*;
import java.math.*;
import java.util.*;
import static java.util.Arrays.fill;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;
public class D854
{
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int m = ni();
int k = ni();
int max = 1000005;
ArrayList<Pair> a[] = new ArrayList[max];
ArrayList<Pair> b[] = new ArrayList[max];
for (int i = 0; i < max; i++)
{
a[i] = new ArrayList<>();
b[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++)
{
int d = ni();
int f = ni();
int t = ni();
int c = ni();
if (t == 0)
{
a[d].add(new Pair(f, c));
} else
{
b[d].add(new Pair(t, c));
}
}
int lcnt[] = new int[max];
int rcnt[] = new int[max];
long ans = Long.MAX_VALUE;
int lcost[] = new int[n + 1];
int rcost[] = new int[n + 1];
long l[] = new long[max];
long r[] = new long[max];
for (int i = 1; i < max; i++)
{
lcnt[i] = lcnt[i - 1];
l[i] = l[i - 1];
for (Pair p : a[i])
{
if (lcost[p.u] == 0)
lcnt[i]++;
if (lcost[p.u] == 0 || lcost[p.u] > p.v)
{
l[i] = l[i] - lcost[p.u] + p.v;
lcost[p.u] = p.v;
}
}
}
for (int i = max - 2; i >= 0; i--)
{
rcnt[i] = rcnt[i + 1];
r[i] = r[i + 1];
for (Pair p : b[i])
{
if (rcost[p.u] == 0)
rcnt[i]++;
if (rcost[p.u] == 0 || rcost[p.u] > p.v)
{
r[i] = r[i] - rcost[p.u] + p.v;
rcost[p.u] = p.v;
}
}
}
for (int i = 0; i < max - k - 1; i++)
if (lcnt[i] == n && rcnt[i + k + 1] == n)
ans = min(ans, l[i] + r[i + k + 1]);
if(ans==Long.MAX_VALUE)
ans = -1;
out.println(ans);
}
class Pair implements Comparable<Pair>
{
int u;
int v;
public Pair(int u, int v)
{
this.u = u;
this.v = v;
}
public int hashCode()
{
return Objects.hash();
}
public boolean equals(Object o)
{
Pair other = (Pair) o;
return u == other.u && v == other.v;
}
public int compareTo(Pair other)
{
return Integer.compare(u, other.u) != 0 ? -1 * Integer.compare(u, other.u)
: -1 * Integer.compare(v, other.v);
}
public String toString()
{
return "[u=" + u + ", v=" + v + "]";
}
}
void run() throws Exception
{
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
if (!INPUT.isEmpty())
tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception
{
new Thread(null, new Runnable()
{
public void run()
{
try
{
new D854().run();
} catch (Exception e)
{
e.printStackTrace();
}
}
}, "1", 1 << 26).start();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf)
{
ptrbuf = 0;
try
{
lenbuf = is.read(inbuf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c)
{
return !(c >= 33 && c <= 126);
}
private int skip()
{
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
private double nd()
{
return Double.parseDouble(ns());
}
private char nc()
{
return (char) skip();
}
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b)))
{ // when nextLine, (isSpaceChar(b) && b !=
// ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b)))
{
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-')
{
minus = true;
b = readByte();
}
while (true)
{
if (b >= '0' && b <= '9')
{
num = num * 10 + (b - '0');
} else
{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-')
{
minus = true;
b = readByte();
}
while (true)
{
if (b >= '0' && b <= '9')
{
num = num * 10 + (b - '0');
} else
{
return minus ? -num : num;
}
b = readByte();
}
}
private void tr(Object... o)
{
System.out.println(Arrays.deepToString(o));
}
}
| JAVA |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | /**
* Created by Aminul on 9/6/2017.
*/
import java.io.*;
import java.util.*;
public class CF854D_uwi_reader {
public static int index;
public static void main(String[] args)throws Exception {
FastReader in = new FastReader(System.in);
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
int n = in.nextInt(), m = in.nextInt(), k = in.nextInt();
long inf = (long)1e12;
int maxN = (int)1e6;
List<Node> list[] = new List[maxN+1];
for(int i = 0; i <= maxN; i++){
list[i] = new ArrayList<>();
}
for(int i = 1; i <= m; i++){
int d = in.nextInt(), f = in.nextInt(), t = in.nextInt(), c = in.nextInt();
list[d].add(new Node(d, f, t, c));
}
long totalSum = 0;
int totalN = 0;
long pre[] = new long[maxN+1];
long suf[] = new long[maxN+1];
int preN[] = new int[maxN+1];
int sufN[] = new int[maxN+1];
long[] min = new long[maxN+1];
Arrays.fill(min, inf);
for(int i = 1; i <= maxN; i++){
for(Node node : list[i]){
if(node.t == 0){
if(min[node.f] > node.c){
if(min[node.f] == inf){
totalN++;
min[node.f] = 0;
}
totalSum -= min[node.f];
min[node.f] = node.c;
totalSum += min[node.f];
}
}
}
preN[i] = totalN;
pre[i] = totalSum;
}
Arrays.fill(min, inf);
totalN = 0; totalSum = 0;
for(int i = maxN; i >= 1; i--){
for(Node node : list[i]){
if(node.f == 0){
if(min[node.t] > node.c){
if(min[node.t] == inf){
totalN++;
min[node.t] = 0;
}
totalSum -= min[node.t];
min[node.t] = node.c;
totalSum += min[node.t];
}
}
}
sufN[i] = totalN;
suf[i] = totalSum;
}
boolean ok = true;
long ans = inf;
for(int i = 1, j = i+k+1; j <= maxN; i++, j++){
if(preN[i] == n && sufN[j] == n){
ans = Math.min(pre[i] + suf[j], ans);
}
}
if(ans == inf) ans = -1;
pw.println(ans);
pw.close();
}
static class Node implements Comparable<Node>{
int d, f, t;
long c;
Node(int D, int F, int T, long C){
d = D; f = F; t = T; c = C;
}
public int compareTo(Node node){
return d - node.d;
}
public String toString(){
return d+" "+f+" "+t+" "+c;
}
}
static void debug(Object...obj) {
System.err.println(Arrays.deepToString(obj));
}
static class FastReader {
InputStream is;
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
public FastReader(InputStream i){
is = i;
}
public int readByte(){
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
public boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
public int skip() {
int b;
while((b = readByte()) != -1 && isSpaceChar(b));
return b;
}
public double nextDouble() {
return Double.parseDouble(next());
}
public char nextChar() {
return (char)skip();
}
public String next(){
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public int nextInt(){
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
public long nextLong() {
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
}
} | JAVA |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | from sys import stdin, stdout
n,m,k = map(int,stdin.readline().rstrip().split())
arrivalFlightList = []
departureFlightList = []
for _ in range(m):
d,f,t,c = map(int,stdin.readline().rstrip().split())
d-=1
if f==0:
t-=1
departureFlightList.append((d,t,c))
else:
f-=1
arrivalFlightList.append((d,f,c))
arrivalFlightList.sort(key = lambda x:x[0])
currentCostList = [99999999]*n
bestArrivalCostList = [-1]*1000000
startFlightListLen = n
noFlights = set(range(n))
lastTime = -1
for d,t,c in arrivalFlightList:
if startFlightListLen>0:
startFlightListLen = len(noFlights)
noFlights.discard(t)
if startFlightListLen==1 and len(noFlights) == 0:
currentCostList[t] = c
bestArrivalCostList[d] = sum(currentCostList)
startFlightListLen = 0
elif lastTime!=d:
for i in range(lastTime+1,d+1):
bestArrivalCostList[i] = bestArrivalCostList[lastTime]
if c<currentCostList[t]:
if startFlightListLen==0:
bestArrivalCostList[d] -= currentCostList[t]-c
currentCostList[t] = c
lastTime = d
for i in range(lastTime+1,1000000):
bestArrivalCostList[i] = bestArrivalCostList[lastTime]
departureFlightList.sort(key = lambda x:x[0],reverse=True)
currentCostList = [99999999]*n
departureCostList = [-1]*1000000
startFlightListLen = n
noFlights = set(range(n))
lastTime = -1
for d,t,c in departureFlightList:
if startFlightListLen>0:
startFlightListLen = len(noFlights)
noFlights.discard(t)
if startFlightListLen==1 and len(noFlights) == 0:
currentCostList[t] = c
departureCostList[d] = sum(currentCostList)
startFlightListLen = 0
elif lastTime!=d:
for i in range(lastTime-1,d-1,-1):
departureCostList[i] = departureCostList[lastTime]
if c<currentCostList[t]:
if startFlightListLen==0:
departureCostList[d] -= currentCostList[t]-c
currentCostList[t] = c
lastTime = d
for i in range(lastTime-1,-1,-1):
departureCostList[i] = departureCostList[lastTime]
bestCost = -1
for i in range(1000000-(k+1)):
if bestArrivalCostList[i]>0 and departureCostList[i+k+1]>0:
if bestCost<0:
bestCost = bestArrivalCostList[i]+departureCostList[i+k+1]
elif bestCost>bestArrivalCostList[i]+departureCostList[i+k+1]:
bestCost = bestArrivalCostList[i]+departureCostList[i+k+1]
print(bestCost)
| PYTHON3 |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
long long costin0[1000110];
long long costout0[1000110];
int nrajuns[1000110];
int nrplecat[1000110];
void set_ajuns(vector<pair<int, int>>& v) {
sort(v.begin(), v.end());
if (v.empty()) return;
nrajuns[v[0].first]++;
for (int i(0); i < v.size(); i++) {
if (i) v[i].second = min(v[i].second, v[i - 1].second);
costin0[v[i].first] += v[i].second;
if (i + 1 < v.size()) costin0[v[i + 1].first] -= v[i].second;
}
}
void set_plecat(vector<pair<int, int>>& v) {
sort(v.begin(), v.end(),
[](pair<int, int>& a, pair<int, int>& b) { return a > b; });
if (v.empty()) return;
nrplecat[v[0].first]++;
for (int i(0); i < v.size(); i++) {
if (i) v[i].second = min(v[i].second, v[i - 1].second);
costout0[v[i].first] += v[i].second;
if (i + 1 < v.size()) costout0[v[i + 1].first] -= v[i].second;
}
}
vector<pair<int, int>> orasep[100010], orasea[100010];
int main() {
int n, m, k;
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m >> k;
int t, p, a, c;
while (m--) {
cin >> t >> p >> a >> c;
if (p == 0)
orasea[a].push_back({t, c});
else
orasep[p].push_back({t, c});
}
for (int i(1); i <= n; i++) set_ajuns(orasep[i]), set_plecat(orasea[i]);
for (int i(1); i <= 1000010; i++)
nrajuns[i] += nrajuns[i - 1], costin0[i] += costin0[i - 1];
for (int i(1000010); i >= 0; i--)
nrplecat[i] += nrplecat[i + 1], costout0[i] += costout0[i + 1];
long long ans(2000000000000ll);
for (int i(1); i + k <= 1000010; i++) {
if (nrajuns[i - 1] == n && nrplecat[i + k] == n)
ans = min(ans, costin0[i - 1] + costout0[i + k]);
}
cout << (ans == 2000000000000ll ? -1ll : ans);
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
inline int read() {
int x;
char c;
while ((c = getchar()) < '0' || c > '9')
;
for (x = c - '0'; (c = getchar()) >= '0' && c <= '9';)
x = (x << 3) + (x << 1) + c - '0';
return x;
}
vector<pair<pair<int, int>, int> > v[1000000 + 5];
long long l[1000000 + 5], r[1000000 + 5], s[100000 + 5], ans = 1e18;
int main() {
int n, m, k, a, b, c, i, j;
n = read();
m = read();
k = read();
while (m--)
a = read(), b = read(), c = read(),
v[a].push_back(make_pair(make_pair(b, c), read()));
for (i = 1; i <= n; ++i) s[i] = 1e13;
for (l[0] = n * 1e13, i = 1; i <= 1000000; ++i)
for (l[i] = l[i - 1], j = 0; j < v[i].size(); ++j)
if (!v[i][j].first.second && v[i][j].second < s[a = v[i][j].first.first])
l[i] += v[i][j].second - s[a], s[a] = v[i][j].second;
for (i = 1; i <= n; ++i) s[i] = 1e13;
for (r[1000000 + 1] = n * 1e13, i = 1000000; i; --i)
for (r[i] = r[i + 1], j = 0; j < v[i].size(); ++j)
if (!v[i][j].first.first && v[i][j].second < s[a = v[i][j].first.second])
r[i] += v[i][j].second - s[a], s[a] = v[i][j].second;
for (i = 1; i + k + 1 <= 1000000; ++i)
if (l[i] + r[i + k + 1] < ans) ans = l[i] + r[i + k + 1];
printf("%I64d", ans < 1e13 ? ans : -1);
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.stream.Stream;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Pradyumn Agrawal coderbond007 PLEASE!! PLEASE!! HACK MY SOLUTION!!
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, FastReader in, PrintWriter out) {
Debug debug = new Debug(out);
int n = in.nextInt(), m = in.nextInt(), k = in.nextInt();
int MAX_DAYS = (int) 1e6 + 10;
ArrayList<TaskB.Query> dayQueries[] = CollectionUtils.generateArrayListArray(MAX_DAYS);
for (int i = 0; i < m; ++i) {
int d = in.nextInt();
TaskB.Query q = new TaskB.Query(in.nextInt(), in.nextInt(), in.nextInt());
dayQueries[d].add(q);
}
long minCostSoFar[] = ArrayUtils.createArray(n + 1, (long) (1e12));
long[] cumMinCostArrival = new long[MAX_DAYS];
for (int i = 1; i <= n; ++i) cumMinCostArrival[0] += minCostSoFar[i];
for (int i = 1; i < MAX_DAYS; ++i) {
cumMinCostArrival[i] += cumMinCostArrival[i - 1];
for (TaskB.Query q : dayQueries[i]) {
if (q.to == 0) {
if (minCostSoFar[q.from] > q.cost) {
cumMinCostArrival[i] = cumMinCostArrival[i] - minCostSoFar[q.from] + q.cost;
minCostSoFar[q.from] = q.cost;
}
}
}
}
ArrayUtils.fill(minCostSoFar, (long) (1e12));
long[] cumMinCostDeparture = new long[MAX_DAYS];
for (int i = 1; i <= n; ++i) cumMinCostDeparture[MAX_DAYS - 1] += minCostSoFar[i];
for (int i = MAX_DAYS - 2; i >= 1; --i) {
cumMinCostDeparture[i] = cumMinCostDeparture[i + 1];
for (TaskB.Query q : dayQueries[i]) {
if (q.from == 0) {
if (minCostSoFar[q.to] > q.cost) {
cumMinCostDeparture[i] = cumMinCostDeparture[i] - minCostSoFar[q.to] + q.cost;
minCostSoFar[q.to] = q.cost;
}
}
}
}
long best = (long) 1e12;
for (int startContestDay = 1; startContestDay <= MAX_DAYS; startContestDay++) {
int endContestDay = startContestDay + k - 1;
if (endContestDay + 1 < MAX_DAYS)
best = Math.min(best, cumMinCostArrival[startContestDay - 1] + cumMinCostDeparture[endContestDay + 1]);
}
out.println(best > 1L * m * (long) 1e6 ? -1 : best);
}
static class Query {
int from;
int to;
int cost;
Query(int f, int t, int c) {
from = f;
to = t;
cost = c;
}
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int pnumChars;
private FastReader.SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
private int pread() {
if (pnumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= pnumChars) {
curChar = 0;
try {
pnumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (pnumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = pread();
while (isSpaceChar(c))
c = pread();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = pread();
}
int res = 0;
do {
if (c == ',') {
c = pread();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = pread();
} while (!isSpaceChar(c));
return res * sgn;
}
private boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
private static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class Debug {
PrintWriter out;
public Debug(PrintWriter out) {
this.out = out;
}
}
static class ArrayUtils {
public static void fill(long[] array, long value) {
Arrays.fill(array, value);
}
public static long[] createArray(int count, long value) {
long[] array = new long[count];
Arrays.fill(array, value);
return array;
}
}
static class CollectionUtils {
public static <E> ArrayList<E>[] generateArrayListArray(int size) {
return Stream.generate(ArrayList::new).limit(size).toArray(ArrayList[]::new);
}
}
}
| JAVA |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | import java.util.*;
import java.math.*;
import java.io.*;
import java.text.*;
public class A {
static class Node implements Comparable<Node>{
int day;
int f;
int t;
long cost;
public Node(int day ,int f,int t,long cost){
this.cost=cost;
this.day=day;
this.f=f;
this.t=t;
}
public int compareTo(Node c){
int i=Long.compare(this.day,c.day);
if(i!=0) return i;
return i;
}
}
//public static PrintWriter pw;
public static PrintWriter pw = new PrintWriter(System.out);
public static void solve() throws IOException {
// pw=new PrintWriter(new FileWriter("C:\\Users\\shree\\Downloads\\small_output_in"));
FastReader sc = new FastReader();
int MX=1000001;
int n=sc.I(); int m=sc.I(); int k=sc.I();
ArrayList<Node> v1[]=new ArrayList[n+1];
ArrayList<Node> v2[]=new ArrayList[n+1];
for(int i=1;i<=n;i++){
v1[i]=new ArrayList<>();
v2[i]=new ArrayList<>();
}
for(int i=1;i<=m;i++) {
int day=sc.I(); int f=sc.I(); int t=sc.I(); long cost=sc.L();
if(f==0) v1[t].add(new Node(day,f,t,cost));
else v2[f].add(new Node(day,f,t,cost));
}
for(int i=1;i<=n;i++) {
Collections.sort(v1[i]);
Collections.sort(v2[i]);
}
long sum1[]=new long[MX];
long sum2[]=new long[MX];
int cnt1[]=new int[MX];
int cnt2[]=new int[MX];
for(int i=1;i<=n;i++){ long mn=Integer.MAX_VALUE;
for(int j=0;j<v2[i].size();j++){
Node p=v2[i].get(j);
mn=Math.min(mn,p.cost);
sum1[p.day]+=mn;
cnt1[p.day]++;
if(j+1<v2[i].size()){
Node p2=v2[i].get(j+1);
sum1[p2.day]-=mn;
cnt1[p2.day]--;
}
}
mn=Integer.MAX_VALUE;
for(int j=v1[i].size()-1;j>=0;j--){
Node p=v1[i].get(j);
mn=Math.min(mn,p.cost);
sum2[p.day]+=mn;
cnt2[p.day]++;
if(j-1>=0){
Node p2=v1[i].get(j-1);
sum2[p2.day]-=mn;
cnt2[p2.day]--;
}
}
}
for(int i=1;i<MX;i++){
sum1[i]=sum1[i]+sum1[i-1];
cnt1[i]=cnt1[i]+cnt1[i-1];
}
for(int i=MX-2;i>=0;i--) {
sum2[i]=sum2[i]+sum2[i+1];
cnt2[i]=cnt2[i]+cnt2[i+1];
}
long ans=Long.MAX_VALUE;
for(int i=1;i+k+1<MX;i++){
if(cnt1[i]==n && cnt2[i+k+1]==n){
ans=Math.min(ans,sum1[i]+sum2[i+k+1]);
}
}
if(ans==Long.MAX_VALUE) pw.println(-1);
else
pw.println(ans);
pw.close();
}
public static void main(String[] args) {
new Thread(null, new Runnable() {
public void run() {
try {
solve();
} catch (Exception e) {
e.printStackTrace();
}
}
}, "1", 1 << 26).start();
}
static BufferedReader br;
static long M = (long) 1e9 + 7;
static class FastReader {
StringTokenizer st;
public FastReader() throws FileNotFoundException {
//br=new BufferedReader(new FileReader("C:\\Users\\shree\\Downloads\\B-small-practice.in"));
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int I() {
return Integer.parseInt(next());
}
long L() {
return Long.parseLong(next());
}
double D() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public boolean hasNext() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String s = br.readLine();
if (s == null) {
return false;
}
st = new StringTokenizer(s);
}
return true;
}
}
} | JAVA |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
template <typename T>
void resize(int n, vector<T> &u) {
u.resize(n);
}
template <typename Head, typename... Tail>
void resize(int n, Head &H, Tail &...T) {
resize(n, H);
resize(n, T...);
}
template <typename T>
void debug_out(T t) {
cerr << t;
}
template <typename A, typename B>
void debug_out(pair<A, B> &u) {
cerr << "(" << u.first << " " << u.second << ")";
}
template <typename T>
void debug_out(vector<T> &t) {
int sz = t.size();
for (int i = 0; i < sz; i++) {
debug_out(t[i]);
if (i != sz - 1) cerr << ", ";
}
}
template <typename T>
void debug_out(vector<vector<T>> &t) {
int sz = t.size();
for (int i = 0; i < sz; i++) {
debug_out(t[i]);
if (i != sz - 1) cerr << endl;
}
}
vector<char> lowchar = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
vector<char> hichar = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
vector<char> base_10 = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
template <typename T>
string to_string(T t) {
ostringstream ss;
ss << t;
return ss.str();
}
long long to_num(string t) {
long long res = 0;
for (int i = 0; i < (int)t.length(); i++) {
res *= 10;
res += t[i] - '0';
}
return res;
}
const int MAX = 1e6 + 5;
int n, m, k, cl, cr;
long long sl, sr;
vector<int> c;
vector<vector<pair<int, int>>> day(MAX);
vector<multiset<int>> l, r;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m >> k;
resize(n + 1, l, r);
for (int i = 0; i < m; i++) {
int d, f, t, c;
cin >> d >> f >> t >> c;
day[d].emplace_back(c, t - f);
}
for (int i = MAX; i > k; i--) {
for (auto j : day[i]) {
if (j.second < 0) continue;
if (!r[j.second].size()) {
cr++;
sr += j.first;
} else {
if (j.first < *r[j.second].begin())
sr += j.first - *r[j.second].begin();
}
r[j.second].insert(j.first);
}
}
long long res = LLONG_MAX;
for (int i = k + 1; i < MAX; i++) {
for (auto j : day[i - k]) {
if (j.second > 0) continue;
if (!l[-j.second].size()) {
cl++;
sl += j.first;
} else {
if (j.first < *l[-j.second].begin())
sl += j.first - *l[-j.second].begin();
}
l[-j.second].insert(j.first);
}
for (auto j : day[i]) {
if (j.second < 0) continue;
int u = *r[j.second].begin();
auto it = r[j.second].find(j.first);
r[j.second].erase(it);
if (r[j.second].empty()) {
cr--;
sr -= j.first;
} else {
sr = sr - u + *r[j.second].begin();
}
}
if (cr + cl == 2 * n) {
res = min(res, sr + sl);
}
}
if (res == LLONG_MAX)
cout << -1;
else
cout << res;
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
struct flight {
int d;
int f;
int t;
int c;
};
vector<struct flight> infor;
int pre[100001];
int aft[100001];
long long sum_com[1000001];
long long sum_go[1000001];
int cmp(struct flight x, struct flight y) {
if (x.d < y.d)
return 1;
else
return 0;
}
int main() {
int n, m, k;
scanf("%d%d%d", &n, &m, &k);
if (m == 0) {
printf("-1");
return 0;
}
struct flight tem;
int i;
for (i = 0; i < m; i++) {
scanf("%d%d%d%d", &(tem.d), &(tem.f), &(tem.t), &(tem.c));
infor.push_back(tem);
}
sort(infor.begin(), infor.end(), cmp);
int max_time = (infor[m - 1]).d;
for (i = 1; i <= n; i++) {
pre[i] = 10000000;
aft[i] = 10000000;
}
int from;
int cost;
int to;
int day;
int sig = 0;
for (i = 0; i < m; i++) {
cost = (infor[i]).c;
from = (infor[i]).f;
day = (infor[i]).d;
if (from != 0) {
if (cost < pre[from]) {
if (pre[from] == 10000000) sig++;
pre[from] = cost;
}
if (sig == n) break;
}
}
long long sum = 0;
int j;
for (j = 1; j <= n; j++) {
sum += pre[j];
}
sum_com[day] = sum;
int p;
for (i++, p = day + 1; i < m; i++) {
cost = (infor[i]).c;
from = (infor[i]).f;
day = (infor[i]).d;
if (from != 0) {
if (cost < pre[from]) {
while (p < day) sum_com[p++] = sum;
p++;
sum = sum - pre[from] + cost;
sum_com[day] = sum;
pre[from] = cost;
}
}
}
while (p <= max_time) sum_com[p++] = sum;
sig = 0;
for (i = m - 1; i >= 0; i--) {
cost = (infor[i]).c;
to = (infor[i]).t;
day = (infor[i]).d;
if (to != 0) {
if (cost < aft[to]) {
if (aft[to] == 10000000) sig++;
aft[to] = cost;
}
if (sig == n) break;
}
}
sum = 0;
for (j = 1; j <= n; j++) {
sum += aft[j];
}
sum_go[day] = sum;
for (i--, p = day - 1; i >= 0; i--) {
cost = (infor[i]).c;
to = (infor[i]).t;
day = (infor[i]).d;
if (to != 0) {
if (cost < aft[to]) {
while (p > day) sum_go[p--] = sum;
p--;
sum = sum - aft[to] + cost;
sum_go[day] = sum;
aft[to] = cost;
}
}
}
while (p >= 1) sum_go[p--] = sum;
long long min_ = -1;
for (i = 1; i <= max_time - k - 1; i++) {
if ((sum_com[i] == 0) || (sum_go[i + k + 1] == 0))
continue;
else {
sum = sum_com[i] + sum_go[i + k + 1];
if (min_ == -1)
min_ = sum;
else if (sum < min_) {
min_ = sum;
}
}
}
printf("%I64d", min_);
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const long long INF = 1e18 + 1;
const int MAXN = 2e6 + 7;
struct mov {
int to, day, cost;
bool operator<(const mov& o) const { return day < o.day; }
};
vector<mov> in, out;
int vis[MAXN];
long long sum[MAXN], mn[MAXN];
int main() {
int n, m, k;
scanf("%d%d%d", &n, &m, &k);
for (int i = 0; i < m; i++) {
int a, b, c, d;
cin >> a >> b >> c >> d;
if (!c) {
in.push_back(mov{b, a, d});
} else {
out.push_back(mov{c, a, d});
}
}
sort(in.begin(), in.end());
sort(out.begin(), out.end());
reverse(out.begin(), out.end());
for (int i = 0; i < MAXN; i++) sum[i] = INF;
int cnt = 0;
long long tmp = 0;
for (mov mv : out) {
if (!vis[mv.to]) {
mn[mv.to] = mv.cost;
tmp += mv.cost;
vis[mv.to] = 1;
cnt++;
} else {
if (mv.cost < mn[mv.to]) {
tmp += mv.cost - mn[mv.to];
mn[mv.to] = mv.cost;
}
}
if (cnt == n) {
sum[mv.day] = tmp;
}
}
for (int i = MAXN - 4; i >= 0; i--) {
if (sum[i] == INF && sum[i + 1] != INF) sum[i] = sum[i + 1];
}
memset(vis, 0, sizeof vis);
tmp = 0;
cnt = 0;
long long ans = INF;
int mxday = 0;
for (mov mv : in) {
if (!vis[mv.to]) {
mn[mv.to] = mv.cost;
tmp += mv.cost;
vis[mv.to] = 1;
cnt++;
} else {
if (mv.cost < mn[mv.to]) {
tmp += mv.cost - mn[mv.to];
mn[mv.to] = mv.cost;
}
}
mxday = mv.day;
if (cnt == n) {
ans = min(ans, tmp + sum[mxday + k + 1]);
}
}
if (ans == INF)
puts("-1");
else
cout << ans << endl;
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | import java.io.*;
import java.util.*;
import static java.lang.Math.min;
/**
* Created by Katushka on 11.03.2020.
*/
public class C {
public static final Comparator<int[]> COMPARATOR = Comparator.comparingInt(o -> o[0]);
static int[] readArray(int size, InputReader in) {
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = in.nextInt();
}
return a;
}
static long[] readLongArray(int size, InputReader in) {
long[] a = new long[size];
for (int i = 0; i < size; i++) {
a[i] = in.nextLong();
}
return a;
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int maxD = 0;
List<int[]> toFlights = new ArrayList<>();
List<int[]> fromFlights = new ArrayList<>();
for (int i = 0; i < m; i++) {
int d = in.nextInt();
int f = in.nextInt();
int t = in.nextInt();
int c = in.nextInt();
maxD = Math.max(d, maxD);
if (f == 0) {
fromFlights.add(new int[]{d, t, c});
} else {
toFlights.add(new int[]{d, f, c});
}
}
toFlights.sort(Comparator.comparingInt(o -> o[0]));
fromFlights.sort(Comparator.comparingInt(o -> o[0]));
Map<Integer, Integer> toBestFlights = new HashMap<>();
int startFlights = 0;
int startToTime = -1;
long[] bestToSum = new long[maxD + 1];
long sum = 0;
int oldD = -1;
long oldSum = 0;
for (int i = 0; i < toFlights.size(); i++) {
int[] toFlight = toFlights.get(i);
if (!toBestFlights.containsKey(toFlight[1])) {
if (startFlights == n - 1) {
startToTime = toFlight[0];
}
startFlights++;
toBestFlights.put(toFlight[1], toFlight[2]);
sum = sum + toFlight[2];
} else {
sum -= toBestFlights.get(toFlight[1]);
toBestFlights.put(toFlight[1], min(toBestFlights.get(toFlight[1]), toFlight[2]));
sum = sum + toBestFlights.get(toFlight[1]);
}
if (startFlights == n) {
for (int j = oldD + 1; j < toFlight[0]; j++) {
bestToSum[j] = oldSum;
}
bestToSum[toFlight[0]] = sum;
}
oldD = toFlight[0];
oldSum = sum;
}
if (startFlights == n) {
for (int j = oldD + 1; j < maxD + 1; j++) {
bestToSum[j] = oldSum;
}
}
Map<Integer, Integer> fromBestFlights = new HashMap<>();
startFlights = 0;
int startFromTime = -1;
long[] bestFromSum = new long[maxD + 1];
sum = 0;
oldD = maxD + 1;
oldSum = 0;
for (int i = fromFlights.size() - 1; i >= 0; i--) {
int[] fromFlight = fromFlights.get(i);
if (!fromBestFlights.containsKey(fromFlight[1])) {
if (startFlights == n - 1) {
startFromTime = fromFlight[0];
}
startFlights++;
fromBestFlights.put(fromFlight[1], fromFlight[2]);
sum = sum + fromFlight[2];
} else {
sum -= fromBestFlights.get(fromFlight[1]);
fromBestFlights.put(fromFlight[1], min(fromBestFlights.get(fromFlight[1]), fromFlight[2]));
sum = sum + fromBestFlights.get(fromFlight[1]);
}
if (startFlights == n) {
for (int j = oldD - 1; j > fromFlight[0]; j--) {
bestFromSum[j] = oldSum;
}
bestFromSum[fromFlight[0]] = sum;
}
oldD = fromFlight[0];
oldSum = sum;
}
if (startFlights == n) {
for (int j = oldD - 1; j >= 0; j--) {
bestFromSum[j] = oldSum;
}
}
if (startToTime == -1 || startFromTime == -1 || startFromTime - startToTime - 1 < k) {
out.println(-1);
out.close();
return;
}
long ans = Long.MAX_VALUE;
for (int i = startToTime; i + k < startFromTime; i++) {
ans = min(ans, bestFromSum[i + k + 1] + bestToSum[i]);
}
out.println(ans);
out.close();
}
private static void outputArray(List<Integer> ans, PrintWriter out) {
StringBuilder str = new StringBuilder();
for (int an : ans) {
str.append(an).append(" ");
}
out.println(str);
}
private static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextString() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public char nextChar() {
return next().charAt(0);
}
}
} | JAVA |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Random;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Wolfgang Beyer
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public static Flight[] shuffle(Flight[] a, Random gen) {
for (int i = 0, n = a.length; i < n; i++) {
int ind = gen.nextInt(n - i) + i;
Flight d = a[i];
a[i] = a[ind];
a[ind] = d;
}
return a;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
int cityAnz = in.nextInt();
int flightAnz = in.nextInt();
int k = in.nextInt();
Flight[] flights = new Flight[flightAnz];
for (int i = 0; i < flightAnz; i++) {
flights[i] = new Flight(in.nextInt(), in.nextInt(), in.nextInt(), in.nextInt());
}
// SHUFFLE
flights = shuffle(flights, new Random());
Arrays.sort(flights);
long[] current = new long[cityAnz + 1];
long currentSum = 0;
Arrays.fill(current, -1);
int arrivals = 0;
long[] arrivalCost = new long[1000001];
int flightIndex = 0;
for (int i = 1; i <= 1000000; i++) {
while ((flightIndex < flightAnz) && (flights[flightIndex].day <= i)) {
if (flights[flightIndex].departure > 0) {
if (current[flights[flightIndex].departure] == -1) {
current[flights[flightIndex].departure] = flights[flightIndex].cost;
currentSum += flights[flightIndex].cost;
arrivals++;
} else if (current[flights[flightIndex].departure] > flights[flightIndex].cost) {
currentSum -= current[flights[flightIndex].departure];
current[flights[flightIndex].departure] = flights[flightIndex].cost;
currentSum += flights[flightIndex].cost;
}
}
flightIndex++;
}
if (arrivals == cityAnz) {
arrivalCost[i] = currentSum;
} else {
arrivalCost[i] = -1;
}
}
current = new long[cityAnz + 1];
currentSum = 0;
Arrays.fill(current, -1);
int departures = 0;
long[] departureCost = new long[1000001];
flightIndex = flightAnz - 1;
for (int i = 1000000; i >= 1; i--) {
while ((flightIndex >= 0) && (flights[flightIndex].day >= i)) {
if (flights[flightIndex].destination > 0) {
if (current[flights[flightIndex].destination] == -1) {
current[flights[flightIndex].destination] = flights[flightIndex].cost;
currentSum += flights[flightIndex].cost;
departures++;
} else if (current[flights[flightIndex].destination] > flights[flightIndex].cost) {
currentSum -= current[flights[flightIndex].destination];
current[flights[flightIndex].destination] = flights[flightIndex].cost;
currentSum += flights[flightIndex].cost;
}
}
flightIndex--;
}
if (departures == cityAnz) {
departureCost[i] = currentSum;
} else {
departureCost[i] = -1;
}
}
long result = Long.MAX_VALUE;
for (int i = 1; i <= 1000000 - k - 1; i++) {
if (arrivalCost[i] > 0) {
if (departureCost[i + k + 1] > 0) {
result = Math.min(result, arrivalCost[i] + departureCost[i + k + 1]);
}
}
}
if (result < Long.MAX_VALUE) {
out.println(result);
} else {
out.println(-1);
}
}
class Flight implements Comparable<Flight> {
int day;
int departure;
int destination;
long cost;
public Flight(int d, int f, int t, long c) {
day = d;
departure = f;
destination = t;
cost = c;
}
public int compareTo(Flight o) {
return day - o.day;
}
}
}
static class InputReader {
private static BufferedReader in;
private static StringTokenizer tok;
public InputReader(InputStream in) {
this.in = new BufferedReader(new InputStreamReader(in));
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
try {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
//tok = new StringTokenizer(in.readLine(), ", \t\n\r\f"); //adds commas as delimeter
}
} catch (IOException ex) {
System.err.println("An IOException was caught :" + ex.getMessage());
}
return tok.nextToken();
}
}
}
| JAVA |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* Created by mostafa on 9/4/17.
*/
public class D {
static class Flight{
int time, cost;
}
static class FlightDep extends Flight {
int to;
FlightDep(int time, int to, int cost) {
this.time = time; this.to = to; this.cost = cost;
}
}
static class FlightArr extends Flight {
int from;
FlightArr(int time, int from, int cost) {
this.time = time; this.from = from; this.cost = cost;
}
}
static int max = (int) (1e6 + 1);
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
ArrayList<FlightDep>[] dep = new ArrayList[(int) (1e6 + 1)];
ArrayList<FlightArr>[] arr = new ArrayList[(int) (1e6 + 1)];
for(int i = 0; i < max; i++) {
dep[i] = new ArrayList<>();
arr[i] = new ArrayList<>();
}
while(m-->0) {
int t = sc.nextInt(), f = sc.nextInt(), to = sc.nextInt(), c = sc.nextInt();
Flight fl;
if(f == 0)
dep[t].add(new FlightDep(t, to, c));
else
arr[t].add(new FlightArr(t, f, c));
}
int[] countBehind = new int[(int) (1e6 + 1)], countFor = new int[(int)(1e6 + 1)];
TreeMap<Integer, Integer> metBehind = new TreeMap<>(), metForward = new TreeMap<>();
long[] minBehind = new long[max], minForward = new long[max];
for(int i = max - 1; i >= 0; i--) {
if(i < max - 1)
minBehind[i] = minBehind[i + 1];
for(FlightDep f: dep[i]) {
int curCost = f.cost;
if(metBehind.containsKey(f.to)) {
int diff = f.cost - metBehind.get(f.to);
if(diff < 0)
minBehind[i] += diff;
curCost = Math.min(curCost, metBehind.get(f.to));
}
else {
minBehind[i] += curCost;
}
metBehind.put(f.to, curCost);
}
countBehind[i] = metBehind.size();
}
for(int i = 0; i < max; i++) {
if(i > 0)
minForward[i] = minForward[i - 1];
for(FlightArr f: arr[i]) {
int curCost = f.cost;
if(metForward.containsKey(f.from)) {
int diff = f.cost - metForward.get(f.from);
if(diff < 0)
minForward[i] += diff;
curCost = Math.min(curCost, metForward.get(f.from));
}
else
minForward[i] += curCost;
metForward.put(f.from, curCost);
}
countFor[i] = metForward.size();
}
long ans = Long.MAX_VALUE;
for(int i = 0; i + k + 1 < max; i++)
if(countFor[i] == n && countBehind[i + k + 1] == n) {
ans = Math.min(ans, minForward[i] + minBehind[i + k + 1]);
}
if(ans == Long.MAX_VALUE)
System.out.println(-1);
else
System.out.println(ans);
PrintWriter out = new PrintWriter(System.out);
out.flush();
out.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() throws IOException {
while(st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
}
}
| JAVA |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class B {
static final long INF = (long) 1e12;
public static void main(String[] args) throws NumberFormatException, IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int[] d = new int[m];
int[] f = new int[m];
int[] t = new int[m];
int[] c = new int[m];
for (int i = 0; i < m; i++) {
d[i] = sc.nextInt();
f[i] = sc.nextInt();
t[i] = sc.nextInt();
c[i] = sc.nextInt();
}
long[] go = new long[n + 1];
PriorityQueue<Integer>[]back = new PriorityQueue[n + 1];
for (int i = 0; i <= n; i++) {
go[i] = INF;
back[i] = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return c[o1] - c[o2];
}
});
}
Integer[] ord = new Integer[m];
for (int i = 0; i < m; i++)
ord[i] = i;
Arrays.sort(ord, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return d[o1] - d[o2];
}
});
for (int i = 0; i < m; i++) {
if(d[i] > k && f[i] == 0) {
back[t[i]].add(i);
}
}
long goC = 0;
long backC = 0;
for (int i = 1; i <= n; i++) {
goC += go[i];
if(back[i].isEmpty())
backC += INF;
else
backC += c[back[i].peek()];
}
long ans = goC + backC;
int p1 = 0;
int p2 = 0;
for (int day = 1; day < (int) 1e6; day++) {
while(p1 < m && d[ord[p1]] < day)
p1++;
while(p1 < m && d[ord[p1]] == day) {
if(t[ord[p1]] == 0) {
goC -= go[f[ord[p1]]];
go[f[ord[p1]]] = Math.min(go[f[ord[p1]]], c[ord[p1]]);
goC += go[f[ord[p1]]];
}
p1++;
}
while(p2 < m && d[ord[p2]] < day + k)
p2++;
while(p2 < m && d[ord[p2]] == day + k) {
if(f[ord[p2]] == 0) {
if(d[back[t[ord[p2]]].peek()] <= day + k) {
backC -= c[back[t[ord[p2]]].peek()];
while(!back[t[ord[p2]]].isEmpty() && d[back[t[ord[p2]]].peek()] <= day + k)
back[t[ord[p2]]].remove();
if(back[t[ord[p2]]].isEmpty())
backC += INF;
else
backC += c[back[t[ord[p2]]].peek()];
}
}
p2++;
}
ans = Math.min(ans, backC + goC);
}
if(ans < 1e12)
out.println(ans);
else
out.println(-1);
out.flush();
out.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String file) throws FileNotFoundException{ br = new BufferedReader(new FileReader(file));}
public String next() throws IOException {
while(st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
public long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public double nextDouble() throws IOException
{
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if(x.charAt(0) == '-')
{
neg = true;
start++;
}
for(int i = start; i < x.length(); i++)
if(x.charAt(i) == '.')
{
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
}
else
{
sb.append(x.charAt(i));
if(dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg?-1:1);
}
}
}
| JAVA |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int N = 100100;
const int M = 1010000;
const long long INF = 1e16;
long long sux[M], suy[M], ans, sum;
int b[N], num, n, m, k, n1, n2;
struct edge {
int t, d, w;
edge() {}
edge(int x, int y, int z) {
t = x;
d = y;
w = z;
}
} a[2][N];
bool cmp1(const edge &aa, const edge &bb) { return aa.t < bb.t; }
bool cmp2(const edge &aa, const edge &bb) { return aa.t > bb.t; }
int main() {
int x, y, z, w, T;
while (scanf("%d%d%d", &n, &m, &k) != EOF) {
T = 0;
n1 = n2 = 0;
for (int i = 1; i <= m; i++) {
scanf("%d%d%d%d", &x, &y, &z, &w);
T = max(T, x);
if (z == 0)
a[0][++n1] = edge(x, y, w);
else if (y == 0)
a[1][++n2] = edge(x, z, w);
}
for (int i = 0; i <= T + 10; i++) sux[i] = suy[i] = INF;
sort(a[0] + 1, a[0] + n1 + 1, cmp1);
sort(a[1] + 1, a[1] + n2 + 1, cmp2);
memset(b, 0, sizeof(b));
sum = 0;
num = 0;
for (int i = 1; i <= n1; i++) {
edge &e = a[0][i];
if (b[e.d] == 0) {
b[e.d] = e.w;
sum += e.w;
num++;
} else if (b[e.d] > e.w) {
sum -= (b[e.d] - e.w);
b[e.d] = e.w;
}
if (num == n) {
sux[e.t] = min(sux[e.t], sum);
}
}
memset(b, 0, sizeof(b));
sum = 0;
num = 0;
for (int i = 1; i <= n2; i++) {
edge &e = a[1][i];
if (b[e.d] == 0) {
b[e.d] = e.w;
sum += e.w;
num++;
} else if (b[e.d] > e.w) {
sum -= (b[e.d] - e.w);
b[e.d] = e.w;
}
if (num == n) {
suy[e.t] = min(suy[e.t], sum);
}
}
for (int i = 2; i <= T; i++) sux[i] = min(sux[i - 1], sux[i]);
for (int i = T - 1; i > 0; i--) suy[i] = min(suy[i], suy[i + 1]);
ans = INF;
for (int i = 1; i + 1 + k <= T; i++) {
int j = i + 1 + k;
if (sux[i] == INF || suy[j] == INF) continue;
ans = min(ans, sux[i] + suy[j]);
}
if (ans == INF)
printf("-1\n");
else
printf("%I64d\n", ans);
}
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int N = 100000 + 10;
const int K = 1000000 + 10;
int n, m, k;
long long arr_cost_sum[K];
long long arr_cnt[K];
long long arr_cost[N];
bool arr[N];
long long dep_cost_sum[K];
long long dep_cnt[K];
long long dep_cost[N];
bool dep[N];
struct Flight {
long long d, f, t, c;
};
vector<Flight> fs[2][K];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> n >> m >> k;
for (int i = 0; i < m; ++i) {
Flight f;
cin >> f.d >> f.f >> f.t >> f.c;
if (f.f == 0)
fs[0][f.d].push_back(f);
else
fs[1][f.d].push_back(f);
}
for (int i = 1; i < K; ++i) {
arr_cnt[i] = arr_cnt[i - 1];
arr_cost_sum[i] = arr_cost_sum[i - 1];
for (auto& f : fs[1][i]) {
if (!arr[f.f]) {
arr[f.f] = 1;
++arr_cnt[i];
arr_cost[f.f] = f.c;
arr_cost_sum[i] += f.c;
} else {
if (f.c < arr_cost[f.f]) {
arr_cost_sum[i] += (f.c - arr_cost[f.f]);
arr_cost[f.f] = f.c;
}
}
}
}
for (int i = K - 2; i >= 1; --i) {
dep_cnt[i] = dep_cnt[i + 1];
dep_cost_sum[i] = dep_cost_sum[i + 1];
for (auto& f : fs[0][i]) {
if (!dep[f.t]) {
dep[f.t] = 1;
++dep_cnt[i];
dep_cost[f.t] = f.c;
dep_cost_sum[i] += f.c;
} else {
if (f.c < dep_cost[f.t]) {
dep_cost_sum[i] += (f.c - dep_cost[f.t]);
dep_cost[f.t] = f.c;
}
}
}
}
set<pair<long long, long long>> dep_cost_day;
for (int i = 1; i != K; ++i) {
if (dep_cnt[i] != n) break;
dep_cost_day.insert(pair<long long, long long>(dep_cost_sum[i], i));
}
long long res = -1;
for (int i = 1; i <= k; ++i) {
if (dep_cost_day.size() == 0) break;
dep_cost_day.erase(pair<long long, long long>(dep_cost_sum[i], i));
}
for (int i = 1; i != K; ++i) {
if (dep_cost_day.size() == 0) break;
if (i + k <= K - 2)
dep_cost_day.erase(
pair<long long, long long>(dep_cost_sum[i + k], i + k));
if (dep_cost_day.size() == 0) break;
if (arr_cnt[i] != n) continue;
long long cost = arr_cost_sum[i] + (dep_cost_day.begin()->first);
if (res == -1)
res = cost;
else
res = min(res, cost);
}
cout << res << endl;
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
long long INF = 1e18;
signed main() {
ios_base::sync_with_stdio(0);
long long n, m, k;
cin >> n >> m >> k;
n++;
vector<vector<long long>> mas(m, vector<long long>(4));
for (long long i = 0; i < m; i++) {
cin >> mas[i][0] >> mas[i][1] >> mas[i][2] >> mas[i][3];
}
sort(mas.begin(), mas.end());
long long time = 1e6 + 10;
vector<long long> ans1(time, INF);
vector<long long> ans2(time, INF);
vector<long long> pep(n, INF);
long long koll = 0;
long long ans = 0;
long long i = 0;
for (long long j = 0; j < time; j++) {
while (i < m && mas[i][0] == j) {
long long t, v, u, st;
t = mas[i][0];
v = mas[i][1];
u = mas[i][2];
st = mas[i][3];
if (u == 0) {
if (pep[v] == INF) {
pep[v] = st;
koll++;
ans += st;
} else if (pep[v] > st) {
ans -= pep[v];
pep[v] = st;
ans += st;
}
}
i++;
}
if (koll == n - 1) {
ans1[j] = ans;
}
}
koll = 0;
ans = 0;
for (long long i = 0; i < n; i++) pep[i] = INF;
reverse(mas.begin(), mas.end());
i = 0;
for (long long j = time - 1; j >= 0; j--) {
while (i < m && mas[i][0] == j) {
long long t, v, u, st;
t = mas[i][0];
v = mas[i][1];
u = mas[i][2];
st = mas[i][3];
if (v == 0) {
if (pep[u] == INF) {
pep[u] = st;
koll++;
ans += st;
} else if (pep[u] > st) {
ans -= pep[u];
pep[u] = st;
ans += st;
}
}
i++;
}
if (koll == n - 1) {
ans2[j] = ans;
}
}
ans = -1;
for (long long i = 0; i < time; i++) {
if (i + k + 1 >= time) continue;
if (ans1[i] == INF || ans2[i + k + 1] == INF) continue;
if (ans == -1)
ans = ans1[i] + ans2[i + k + 1];
else
ans = min(ans, ans1[i] + ans2[i + k + 1]);
}
cout << ans;
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
final long inf = Long.MAX_VALUE / 4;
final int maxDay = 1_000_000;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
ArrayList<ticket> tickets = new ArrayList<>();
for (int i = 0; i < m; i++) {
tickets.add(new ticket(in.nextInt(), in.nextInt(), in.nextInt(), in.nextInt()));
}
tickets.sort((ticket f, ticket s) -> f.d - s.d);
int[] cityMinCost = new int[n + 1];
for (int i = 1; i <= n; i++) {
cityMinCost[i] = -1;
}
long citySum = 0;
int arrivalCnt = 0;
long[] cityArrivalCost = new long[maxDay + 1];
for (int i = 0; i <= 1_000_000; i++) {
cityArrivalCost[i] = inf;
}
for (ticket cur : tickets) {
if (cur.f == 0) continue;
if (cityMinCost[cur.f] >= 0) {
if (cityMinCost[cur.f] > cur.c) {
citySum -= cityMinCost[cur.f] - cur.c;
cityMinCost[cur.f] = cur.c;
}
} else {
cityMinCost[cur.f] = cur.c;
citySum += cur.c;
arrivalCnt++;
}
if (arrivalCnt == n) {
cityArrivalCost[cur.d] = citySum;
}
}
for (int i = 1; i <= maxDay; i++) {
cityArrivalCost[i] = Math.min(cityArrivalCost[i - 1], cityArrivalCost[i]);
}
citySum = 0;
int departureCnt = 0;
for (int i = 1; i <= n; i++) {
cityMinCost[i] = -1;
}
long[] cityDepartureCost = new long[maxDay + 1];
for (int i = 0; i <= maxDay; i++) {
cityDepartureCost[i] = inf;
}
for (int i = tickets.size() - 1; i >= 0; i--) {
ticket cur = tickets.get(i);
if (cur.t == 0) continue;
if (cityMinCost[cur.t] >= 0) {
if (cityMinCost[cur.t] > cur.c) {
citySum -= cityMinCost[cur.t] - cur.c;
cityMinCost[cur.t] = cur.c;
}
} else {
cityMinCost[cur.t] = cur.c;
citySum += cur.c;
departureCnt++;
}
if (departureCnt == n) {
cityDepartureCost[cur.d] = citySum;
}
}
for (int i = maxDay; i > 0; i--) {
cityDepartureCost[i - 1] = Math.min(cityDepartureCost[i - 1], cityDepartureCost[i]);
}
long ans = inf;
for (int arrivalDay = 1; ; arrivalDay++) {
int departureDay = arrivalDay + k + 1;
if (departureDay > maxDay) break;
ans = Math.min(ans, cityArrivalCost[arrivalDay] + cityDepartureCost[departureDay]);
}
if (ans == inf) {
out.println(-1);
} else {
out.println(ans);
}
}
}
static class ticket {
int d;
int f;
int t;
int c;
ticket(int d1, int f1, int t1, int c1) {
d = d1;
f = f1;
t = t1;
c = c1;
}
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer stt;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
return null;
}
}
public String next() {
while (stt == null || !stt.hasMoreTokens()) {
stt = new StringTokenizer(nextLine());
}
return stt.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| JAVA |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int n, m, k;
struct F {
int d, u, v, c;
inline bool operator<(const F x) const { return d < x.d; }
} f[100010];
int in[100010];
long long ans = 0, ansans = -1;
vector<int> lv[100010];
int pos[100010];
int T;
inline void init() {
for (int i = 1; i <= m; i++) {
if (f[i].v == 0) continue;
int u = f[i].v, c = f[i].c;
while (lv[u].size() > 0 && f[lv[u][lv[u].size() - 1]].c >= c)
lv[u].pop_back();
lv[u].push_back(i);
}
}
int main() {
scanf("%d%d%d", &n, &m, &k);
T = n;
for (int i = 1; i <= m; i++)
scanf("%d%d%d%d", &f[i].d, &f[i].u, &f[i].v, &f[i].c);
sort(f + 1, f + m + 1);
memset(in, 0x3f, sizeof(in));
for (int i = 1; i <= n; i++) ans += in[i];
init();
for (int i = 1; i <= n; i++)
if (lv[i].size() == 0) {
printf("-1\n");
return 0;
}
for (int i = 1; i <= n; i++) ans += f[lv[i][0]].c;
for (int i = 1, p = 1, q = 1; p <= m; i++) {
while (p <= m && f[p].d == i) {
if (f[p].u == 0) {
p++;
continue;
} else {
ans -= in[f[p].u];
if (in[f[p].u] == 0x3f3f3f3f) T--;
in[f[p].u] = min(in[f[p].u], f[p].c);
ans += in[f[p].u];
p++;
}
}
while (q <= m && f[q].d <= i + k) {
if (f[q].v == 0) {
q++;
continue;
} else {
int u = f[q].v;
if (pos[u] < lv[u].size() && lv[u][pos[u]] == q) {
ans -= f[lv[u][pos[u]]].c;
pos[u]++;
if (pos[u] == lv[u].size()) {
cout << ansans << endl;
return 0;
}
ans += f[lv[u][pos[u]]].c;
}
q++;
}
}
if (!T) {
if (ansans < 0)
ansans = ans;
else
ansans = min(ansans, ans);
}
}
cout << ansans << endl;
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Solution {
public static void main(String[] args) throws Exception {
MyReader reader = new MyReader(System.in);
MyWriter writer = new MyWriter(System.out);
new Solution().run(reader, writer);
writer.close();
}
private void run(MyReader reader, MyWriter writer) throws IOException {
int n = reader.nextInt();
int m = reader.nextInt();
int k = reader.nextInt();
List<A> in = new ArrayList<>();
List<A> out = new ArrayList<>();
for (int i = 0; i < m; i++) {
int d = reader.nextInt();
int f = reader.nextInt();
int t = reader.nextInt();
int c = reader.nextInt();
if (t == 0) {
in.add(new A(d, f, c));
} else {
out.add(new A(d, t, c));
}
}
in.sort(Comparator.comparingInt(e -> e.d));
out.sort(Comparator.comparingInt(e -> e.d));
Map<Integer, Integer> map1 = new HashMap<>();
long q = 1_000_000_000_000_000L;
long[] a1 = new long[1_000_001];
long[] a2 = new long[1_000_001];
int st = -1;
int en = -1;
Arrays.fill(a1, q);
Arrays.fill(a2, q);
long sum = 0;
for (A a : in) {
if (!map1.containsKey(a.f)) {
map1.put(a.f, a.c);
sum += a.c;
} else if (map1.get(a.f) > a.c) {
sum -= map1.get(a.f) - a.c;
map1.put(a.f, a.c);
}
if (map1.size() == n) {
if (st == -1) {
st = a.d + 1;
}
a1[a.d] = sum;
}
}
sum = 0;
map1.clear();
for (int i = out.size() - 1; i >= 0; i--) {
A a = out.get(i);
if (!map1.containsKey(a.f)) {
map1.put(a.f, a.c);
sum += a.c;
} else if (map1.get(a.f) > a.c) {
sum -= map1.get(a.f) - a.c;
map1.put(a.f, a.c);
}
if (map1.size() == n) {
if (en == -1) {
en = a.d - 1;
}
a2[a.d] = sum;
}
}
if (st == -1 || en == -1) {
writer.print(-1);
return;
}
for (int i = 1; i < 1_000_001; i++) {
a1[i] = Math.min(a1[i], a1[i - 1]);
}
for (int i = 999_999; i >= 0; i--) {
a2[i] = Math.min(a2[i], a2[i + 1]);
}
long ans = Long.MAX_VALUE;
for (int i = st; i + k <= en + 1; i++) {
ans = Math.min(ans, a1[i - 1] + a2[i + k]);
}
writer.print(ans >= q ? -1 : ans);
}
class A {
int d;
int f;
int c;
public A(int d, int f, int c) {
this.d = d;
this.f = f;
this.c = c;
}
}
static class MyReader {
final BufferedInputStream in;
final int bufSize = 1 << 16;
final byte buf[] = new byte[bufSize];
int i = bufSize;
int k = bufSize;
final StringBuilder str = new StringBuilder();
MyReader(InputStream in) {
this.in = new BufferedInputStream(in, bufSize);
}
int nextInt() throws IOException {
return (int) nextLong();
}
int[] nextIntArray(int n) throws IOException {
int[] m = new int[n];
for (int i = 0; i < n; i++) {
m[i] = nextInt();
}
return m;
}
int[][] nextIntMatrix(int n, int m) throws IOException {
int[][] a = new int[n][0];
for (int j = 0; j < n; j++) {
a[j] = nextIntArray(m);
}
return a;
}
long nextLong() throws IOException {
int c;
long x = 0;
boolean sign = true;
while ((c = nextChar()) <= 32) ;
if (c == '-') {
sign = false;
c = nextChar();
}
if (c == '+') {
c = nextChar();
}
while (c >= '0') {
x = x * 10 + (c - '0');
c = nextChar();
}
return sign ? x : -x;
}
long[] nextLongArray(int n) throws IOException {
long[] m = new long[n];
for (int i = 0; i < n; i++) {
m[i] = nextLong();
}
return m;
}
int nextChar() throws IOException {
if (i == k) {
k = in.read(buf, 0, bufSize);
i = 0;
}
return i >= k ? -1 : buf[i++];
}
String nextString() throws IOException {
int c;
str.setLength(0);
while ((c = nextChar()) <= 32 && c != -1) ;
if (c == -1) {
return null;
}
while (c > 32) {
str.append((char) c);
c = nextChar();
}
return str.toString();
}
String nextLine() throws IOException {
int c;
str.setLength(0);
while ((c = nextChar()) <= 32 && c != -1) ;
if (c == -1) {
return null;
}
while (c != '\n') {
str.append((char) c);
c = nextChar();
}
return str.toString();
}
char[] nextCharArray() throws IOException {
return nextString().toCharArray();
}
char[][] nextCharMatrix(int n) throws IOException {
char[][] a = new char[n][0];
for (int i = 0; i < n; i++) {
a[i] = nextCharArray();
}
return a;
}
}
static class MyWriter {
final BufferedOutputStream out;
final int bufSize = 1 << 16;
final byte buf[] = new byte[bufSize];
int i = 0;
final byte c[] = new byte[30];
static final String newLine = System.getProperty("line.separator");
MyWriter(OutputStream out) {
this.out = new BufferedOutputStream(out, bufSize);
}
void print(long x) throws IOException {
int j = 0;
if (i + 30 >= bufSize) {
flush();
}
if (x < 0) {
buf[i++] = (byte) ('-');
x = -x;
}
while (j == 0 || x != 0) {
c[j++] = (byte) (x % 10 + '0');
x /= 10;
}
while (j-- > 0)
buf[i++] = c[j];
}
void print(int[] m) throws IOException {
for (int a : m) {
print(a);
print(' ');
}
}
void print(long[] m) throws IOException {
for (long a : m) {
print(a);
print(' ');
}
}
void print(String s) throws IOException {
for (int i = 0; i < s.length(); i++) {
print(s.charAt(i));
}
}
void print(char x) throws IOException {
if (i == bufSize) {
flush();
}
buf[i++] = (byte) x;
}
void print(char[] m) throws IOException {
for (char c : m) {
print(c);
}
}
void println(String s) throws IOException {
print(s);
println();
}
void println() throws IOException {
print(newLine);
}
void flush() throws IOException {
out.write(buf, 0, i);
out.flush();
i = 0;
}
void close() throws IOException {
flush();
out.close();
}
}
} | JAVA |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
struct Node {
int city, cos;
Node() {}
Node(int _city, int _cos) : city(_city), cos(_cos) {}
};
vector<Node> fl[1001000][2];
int mn[100100];
int mx[100100];
int pre[100100];
int suf[100100];
long long presum[1001000];
long long sufsum[1001000];
int main() {
int n, m, k, d, f, t, c;
scanf("%d %d %d", &n, &m, &k);
for (int i = 0; i < m; ++i) {
scanf("%d %d %d %d", &d, &f, &t, &c);
if (f != 0) {
fl[d][0].push_back(Node(f, c));
if (mn[f] == 0)
mn[f] = d;
else
mn[f] = min(mn[f], d);
} else {
fl[d][1].push_back(Node(t, c));
if (mx[t] == 0)
mx[t] = d;
else
mx[t] = max(mx[t], d);
}
}
if (m < 2 * n)
printf("-1\n");
else {
for (int i = 1; i < 1001000; ++i) {
for (int j = 0; j < fl[i][0].size(); ++j) {
Node &tmp = fl[i][0][j];
if (pre[tmp.city] == 0) {
pre[tmp.city] = tmp.cos;
presum[i] += tmp.cos;
} else if (pre[tmp.city] > tmp.cos) {
presum[i] -= pre[tmp.city];
pre[tmp.city] = tmp.cos;
presum[i] += tmp.cos;
}
}
presum[i] += presum[i - 1];
}
for (int i = 1001000 - 2; i; i--) {
for (int j = 0; j < fl[i][1].size(); ++j) {
Node &tmp = fl[i][1][j];
if (suf[tmp.city] == 0) {
suf[tmp.city] = tmp.cos;
sufsum[i] += tmp.cos;
} else if (suf[tmp.city] > tmp.cos) {
sufsum[i] -= suf[tmp.city];
suf[tmp.city] = tmp.cos;
sufsum[i] += tmp.cos;
}
}
sufsum[i] += sufsum[i + 1];
}
int st = 0, en = 1001000, flg = 1;
for (int i = 1; i <= n; ++i) {
st = max(st, mn[i]);
en = min(en, mx[i]);
if (mn[i] == 0 || mx[i] == 0) flg = 0;
}
if (en - st - 1 < k || !flg)
printf("-1\n");
else {
long long ans = 1e18;
for (int i = st; i + k < en; ++i)
ans = min(ans, presum[i] + sufsum[i + k + 1]);
printf("%I64d\n", ans);
}
}
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <class T, class U>
using P = pair<T, U>;
template <class T>
using vec = vector<T>;
template <class T>
using vvec = vector<vec<T>>;
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
ll N, M, K;
cin >> N >> M >> K;
ll inf = 1e18;
int ma = 1e6;
vvec<P<ll, ll>> come(ma + 10), go(ma + 10);
for (int i = 0; i < M; i++) {
int d, f, t, c;
cin >> d >> f >> t >> c;
if (t == 0)
come[d].push_back({f, c});
else
go[d].push_back({t, c});
}
ll ans = inf;
map<int, ll> Lmi;
vec<map<ll, int>> Rmi(N + 1);
map<int, int> cnt;
for (int i = ma; i >= K + 1; i--) {
for (auto& p : go[i]) {
Rmi[p.first][p.second]++;
cnt[p.first]++;
}
}
if (cnt.size() != N) {
cout << -1 << endl;
return 0;
}
ll now = 0;
for (int i = 1; i <= N; i++) now += Rmi[i].begin()->first;
for (auto& p : come[0]) {
if (!Lmi.count(p.first))
Lmi[p.first] = p.second;
else
Lmi[p.first] = min(Lmi[p.first], p.second);
}
for (int i = 1; i <= N; i++)
if (Lmi.count(i)) now += Lmi[i];
if (Lmi.size() == N) ans = now;
for (int i = 1; i + K <= ma; i++) {
for (auto& p : come[i]) {
if (!Lmi.count(p.first)) {
Lmi[p.first] = p.second;
now += p.second;
} else {
if (Lmi[p.first] > p.second) {
now -= Lmi[p.first];
now += p.second;
Lmi[p.first] = p.second;
}
}
}
for (auto& p : go[i + K]) {
cnt[p.first]--;
if (cnt[p.first] == 0) cnt.erase(p.first);
Rmi[p.first][p.second]--;
if (Rmi[p.first][p.second] == 0) {
bool change = (Rmi[p.first].begin()->first) == p.second;
Rmi[p.first].erase(p.second);
if (change) {
now += -p.second + Rmi[p.first].begin()->first;
}
}
}
if (cnt.size() < N) break;
if (Lmi.size() == N) {
ans = min(ans, now);
}
}
cout << (ans != inf ? ans : -1) << endl;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Comparator;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Liavontsi Brechka
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static
@SuppressWarnings("Duplicates")
class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
ArrayList<TaskD.Flight> to = new ArrayList<>();
ArrayList<TaskD.Flight> from = new ArrayList<>();
int day, toCity, fromCity, cost;
for (int i = 0; i < m; i++) {
day = in.nextInt();
fromCity = in.nextInt();
toCity = in.nextInt();
cost = in.nextInt();
if (toCity == 0) {
to.add(new TaskD.Flight(day, fromCity, cost));
} else {
from.add(new TaskD.Flight(day, toCity, cost));
}
}
to.sort(Comparator.comparingInt(o -> o.day));
from.sort(((o1, o2) -> {
if (o1.day == o2.day) return Integer.compare(o1.cost, o2.cost);
else return Integer.compare(o2.day, o1.day);
}));
ArrayList<TaskD.Min> forBack = new ArrayList<>();
ArrayList<TaskD.Min> minBack = new ArrayList<>();
int[] cities = new int[n];
int count = 0;
long sum = 0;
for (TaskD.Flight f : to) {
if (cities[f.city - 1] > 0) {
if (cities[f.city - 1] > f.cost) {
sum -= ((long) cities[f.city - 1]);
cities[f.city - 1] = f.cost;
sum += ((long) cities[f.city - 1]);
}
} else {
cities[f.city - 1] = f.cost;
count++;
sum += ((long) f.cost);
}
if (count == n) {
forBack.add(new TaskD.Min(f.day + k, sum));
}
}
cities = new int[n];
count = 0;
sum = 0;
for (TaskD.Flight f : from) {
if (cities[f.city - 1] > 0) {
if (cities[f.city - 1] > f.cost) {
sum -= ((long) cities[f.city - 1]);
cities[f.city - 1] = f.cost;
sum += ((long) cities[f.city - 1]);
}
} else {
cities[f.city - 1] = f.cost;
count++;
sum += ((long) f.cost);
}
if (count == n) {
minBack.add(new TaskD.Min(f.day, sum));
}
}
Collections.reverse(minBack);
sum = Long.MAX_VALUE;
TaskD.Min next;
for (TaskD.Min r : forBack) {
next = search(minBack, r.day + 1);
if (next != null) {
sum = Math.min(sum, (long) r.cost + next.cost);
}
}
out.print(sum == Long.MAX_VALUE ? -1 : sum);
}
private TaskD.Min search(ArrayList<TaskD.Min> minBack, int day) {
int l = 0;
int r = minBack.size() - 1;
int mid;
while (l < r) {
mid = (l + r) >> 1;
if (minBack.get(mid).day < day) {
l = mid + 1;
} else {
r = mid;
}
}
if (r > -1 && minBack.get(r).day >= day) {
return minBack.get(r);
} else return null;
}
private static class Flight {
int day;
int city;
int cost;
public Flight(int day, int city, int cost) {
this.day = day;
this.city = city;
this.cost = cost;
}
}
private static class Min {
int day;
long cost;
public Min(int day, long cost) {
this.day = day;
this.cost = cost;
}
}
}
static class InputReader {
private final BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(readLine());
}
return tokenizer.nextToken();
}
public String readLine() {
String line;
try {
line = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
}
}
| JAVA |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int MaxN = 1e5, MaxV = 1e6;
const long long inf = 1LL << 60;
int n, m, k;
struct NODE {
int d, u, v, c;
} box[MaxV + 5];
int ok[MaxN + 5];
long long f[MaxV + 5], t[MaxV + 5];
bool cmp(NODE x, NODE y) { return x.d < y.d; }
int main() {
while (~scanf("%d %d %d", &n, &m, &k)) {
for (int i = 1; i <= m; i++)
scanf("%d %d %d %d", &box[i].d, &box[i].u, &box[i].v, &box[i].c);
sort(box + 1, box + m + 1, cmp);
long long tot = 0;
for (int i = 1; i <= 1e6; i++) f[i] = t[i] = inf;
for (int i = 1; i <= m; i++) {
if (box[i].u == 0) continue;
if (ok[box[i].u] == 0) {
ok[0]++;
ok[box[i].u] = box[i].c;
tot = tot + 1LL * box[i].c;
} else {
tot = tot - ok[box[i].u];
ok[box[i].u] = min(ok[box[i].u], box[i].c);
tot = tot + ok[box[i].u];
}
if (ok[0] == n) f[box[i].d] = tot;
}
for (int i = 2; i <= 1e6; i++) f[i] = min(f[i], f[i - 1]);
memset(ok, 0, sizeof(ok));
tot = 0;
for (int i = m; i >= 1; i--) {
if (box[i].v == 0) continue;
if (ok[box[i].v] == 0) {
ok[0]++;
ok[box[i].v] = box[i].c;
tot = tot + 1LL * box[i].c;
} else {
tot = tot - ok[box[i].v];
ok[box[i].v] = min(ok[box[i].v], box[i].c);
tot = tot + ok[box[i].v];
}
if (ok[0] == n) t[box[i].d] = tot;
}
for (int i = 1e6 - 1; i >= 1; i--) t[i] = min(t[i], t[i + 1]);
long long ans = inf;
for (int i = 1; i <= 1e6 - k - 1; i++) {
if (f[i] != inf && t[i + k + 1] != inf)
ans = min(ans, f[i] + t[i + k + 1]);
}
if (ans != inf)
printf("%lld\n", ans);
else
printf("-1\n");
}
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1000010;
const int md = 5e6;
struct node {
int t, v, cost;
bool operator<(const node &nd) const { return t < nd.t; }
};
vector<node> vec1;
vector<node> vec2;
bool vis[maxn];
long long pre[md + 5], suf[md + 5], Min[maxn];
int main() {
int n, m, k, u, v, t, c;
scanf("%d%d%d", &n, &m, &k);
for (int i = 0; i < m; i++) {
scanf("%d%d%d%d", &t, &u, &v, &c);
if (v == 0) {
vec1.push_back((node){t, u, c});
} else
vec2.push_back((node){t, v, c});
}
memset(pre, 0x3f, sizeof(pre));
memset(suf, 0x3f, sizeof(suf));
memset(Min, 0x3f, sizeof(Min));
sort(vec1.begin(), vec1.end());
sort(vec2.begin(), vec2.end());
int cnt = 0;
long long tmp = 0;
for (int i = 0; i < vec1.size(); i++) {
if (!vis[vec1[i].v]) {
cnt++;
tmp += vec1[i].cost;
vis[vec1[i].v] = 1;
Min[vec1[i].v] = vec1[i].cost;
} else {
if (vec1[i].cost < Min[vec1[i].v]) {
tmp -= Min[vec1[i].v] - vec1[i].cost;
Min[vec1[i].v] = vec1[i].cost;
}
}
if (cnt == n) {
pre[vec1[i].t] = min(pre[vec1[i].t], tmp);
}
}
memset(vis, 0, sizeof(vis));
memset(Min, 0x3f, sizeof(Min));
cnt = 0;
tmp = 0;
for (int i = vec2.size() - 1; i > -1; i--) {
if (!vis[vec2[i].v]) {
cnt++;
tmp += vec2[i].cost;
vis[vec2[i].v] = 1;
Min[vec2[i].v] = vec2[i].cost;
} else {
if (vec2[i].cost < Min[vec2[i].v]) {
tmp -= Min[vec2[i].v] - vec2[i].cost;
Min[vec2[i].v] = vec2[i].cost;
}
}
if (cnt == n) {
suf[vec2[i].t] = min(suf[vec2[i].t], tmp);
}
}
for (int i = 1; i <= md; i++) pre[i] = min(pre[i], pre[i - 1]);
for (int i = md; i >= 0; i--) suf[i] = min(suf[i], suf[i + 1]);
long long ans = 1e18;
for (int i = 1; i <= 2e6; i++) {
ans = min(ans, pre[i - 1] + suf[i + k - 1 + 1]);
}
if (ans > 1e15)
puts("-1");
else
printf("%lld\n", ans);
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:10240000")
using namespace std;
const int MAXN = 100010;
struct tnode {
int d, f, t;
long long c;
} a[MAXN];
int sta[MAXN][2];
long long all[MAXN][2], times[MAXN][2];
bool cmp(tnode a, tnode b) { return a.d < b.d; }
int main() {
int n, m, k;
scanf("%d%d%d", &n, &m, &k);
for (int i = 1; i <= m; i++) {
scanf("%d%d%d%I64d", &a[i].d, &a[i].f, &a[i].t, &a[i].c);
}
memset(times, -1, sizeof(times));
int cnt0 = 0, cnt1 = 0, num = 0;
sort(a + 1, a + m + 1, cmp);
for (int i = m; i >= 1; i--) {
if (!a[i].f) {
if (times[a[i].t][0] == -1) {
times[a[i].t][0] = a[i].c;
num++;
if (num == n) {
cnt0++;
all[cnt0][0] = 0;
for (int j = 1; j <= n; j++) {
all[cnt0][0] += times[j][0];
}
sta[cnt0][0] = a[i].d;
}
} else if (a[i].c < times[a[i].t][0]) {
if (num == n) {
cnt0++;
all[cnt0][0] = all[cnt0 - 1][0] - (times[a[i].t][0] - a[i].c);
sta[cnt0][0] = a[i].d;
}
times[a[i].t][0] = a[i].c;
}
}
}
num = 0;
for (int i = 1; i <= m; i++) {
if (!a[i].t) {
if (times[a[i].f][1] == -1) {
times[a[i].f][1] = a[i].c;
num++;
if (num == n) {
cnt1++;
all[cnt1][1] = 0;
for (int j = 1; j <= n; j++) {
all[cnt1][1] += times[j][1];
}
sta[cnt1][1] = a[i].d;
}
} else if (a[i].c < times[a[i].f][1]) {
if (num == n) {
cnt1++;
all[cnt1][1] = all[cnt1 - 1][1] - (times[a[i].f][1] - a[i].c);
sta[cnt1][1] = a[i].d;
}
times[a[i].f][1] = a[i].c;
}
}
}
bool flag = false;
long long ans = -1;
int j = cnt0;
if (j) {
for (int i = 1; i <= cnt1; i++) {
while (sta[j][0] - sta[i][1] <= k) {
j--;
if (j == 0) {
break;
}
}
if (!j) {
break;
}
if ((ans == -1) || (all[i][1] + all[j][0] < ans)) {
ans = all[i][1] + all[j][0];
flag = true;
}
}
}
if (!flag) {
printf("-1\n");
} else {
printf("%I64d\n", ans);
}
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
template <class S, class T>
ostream& operator<<(ostream& o, const pair<S, T>& p) {
return o << "(" << p.first << "," << p.second << ")";
}
template <class T>
ostream& operator<<(ostream& o, const vector<T>& vc) {
o << "sz = " << vc.size() << endl << "[";
for (const T& v : vc) o << v << ",";
o << "]";
return o;
}
long long inf = 1e12;
long long N, M, K;
const int MK = 1000010;
vector<pair<long long, long long> > in[MK], out[MK];
vector<long long> insum(MK, inf), outsum(MK, inf);
int main() {
cin >> N >> M >> K;
for (int i = 0; i < (int)(M); i++) {
int a, b, c, d;
cin >> a >> b >> c >> d;
if (c == 0) {
in[a].push_back(pair<long long, long long>(b - 1, d));
} else {
out[a].push_back(pair<long long, long long>(c - 1, d));
}
}
{
vector<long long> mn(N, inf);
long long sum = N * inf;
for (int i = 0; i < (int)(MK); i++) {
for (pair<long long, long long> p : in[i]) {
int v = p.first;
long long c = p.second;
if (mn[v] > c) {
sum -= mn[v];
mn[v] = c;
sum += mn[v];
}
}
insum[i] = sum;
}
}
{
vector<long long> mn(N, inf);
long long sum = N * inf;
for (int i = MK - 1; i >= 0; i--) {
for (pair<long long, long long> p : out[i]) {
int v = p.first;
long long c = p.second;
if (mn[v] > c) {
sum -= mn[v];
mn[v] = c;
sum += mn[v];
}
}
outsum[i] = sum;
}
}
long long ans = inf;
for (int i = 1; i <= (int)(MK); i++) {
if (i + K >= MK) break;
long long tmp = insum[i - 1] + outsum[i + K];
if (ans > tmp) ans = min(ans, tmp);
}
if (ans == inf)
puts("-1");
else
cout << ans << endl;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
struct pl {
int d, i, c;
};
int n, dmx = 0, k;
long long ci[((int)(1e6)) + 1000], co[((int)(1e6)) + 1000];
int mp[((int)(1e5)) + 1000];
vector<pl> pli, plo;
bool cmpl(const pl &a, const pl &b) { return a.d < b.d; }
bool cmpg(const pl &a, const pl &b) { return a.d > b.d; }
void scani(vector<pl> &pls, long long c[]) {
long long s = 0;
int sz = pls.size(), cnt = 0;
int i, j = 0;
for (i = 0; i <= dmx; i++) {
while (j < sz && pls[j].d <= i) {
int ind = pls[j].i;
if (mp[ind] > pls[j].c) {
s += pls[j].c - mp[ind];
mp[ind] = pls[j].c;
}
if (mp[ind] == -1) {
s += pls[j].c;
mp[ind] = pls[j].c;
cnt++;
}
j++;
}
if (cnt == n)
c[i] = s;
else
c[i] = ((long long)(1e15));
}
}
void scano(vector<pl> &pls, long long c[]) {
long long s = 0;
int sz = pls.size(), cnt = 0;
int i, j = 0;
for (i = dmx; i >= 0; i--) {
while (j < sz && pls[j].d >= i) {
int ind = pls[j].i;
if (mp[ind] > pls[j].c) {
s += pls[j].c - mp[ind];
mp[ind] = pls[j].c;
}
if (mp[ind] == -1) {
s += pls[j].c;
mp[ind] = pls[j].c;
cnt++;
}
j++;
}
if (cnt == n)
c[i] = s;
else
c[i] = ((long long)(1e15));
}
}
int main() {
int m;
int i;
scanf("%d%d%d", &n, &m, &k);
for (i = 0; i < m; i++) {
int d, f, t, c;
scanf("%d%d%d%d", &d, &f, &t, &c);
if (f == 0)
plo.push_back((pl){d, t, c});
else
pli.push_back((pl){d, f, c});
dmx = max(dmx, d);
}
sort(pli.begin(), pli.end(), cmpl);
sort(plo.begin(), plo.end(), cmpg);
memset(mp, -1, sizeof(mp));
scani(pli, ci);
memset(mp, -1, sizeof(mp));
scano(plo, co);
long long mi = ((long long)(1e15)), ans = ((long long)(1e15));
for (i = k; i <= dmx; i++) {
if (mi < ((long long)(1e15)) && co[i] < ((long long)(1e15))) {
ans = min(ans, mi + co[i]);
}
mi = min(mi, ci[i - k]);
}
printf(
"%lld"
"\n",
((ans >= ((long long)(1e15))) ? -1ll : ans));
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int MAX_N = 1e6 + 10;
const long long myINF = 1e12 + 5;
const long long mod = 1e9 + 7;
const long long INF = 1e9;
inline long long bpow(long long t, long long n) {
long long ans = 1;
while (n > 0) {
if (n & 1) ans = (ans * t) % mod;
t = (t * t) % mod, n >>= 1;
}
return ans;
}
long long dpl[MAX_N], dpr[MAX_N], sumleft[MAX_N], sumright[MAX_N];
vector<pair<int, int> > cntsr[MAX_N], cntsl[MAX_N];
long long n, m, k;
void inp() {
cin >> n >> m >> k;
for (long long i = 1, d, f, t, c; i <= m; i++) {
cin >> d >> f >> t >> c;
if (f != 0)
cntsr[d].push_back({f, c});
else
cntsl[d].push_back({t, c});
}
}
void pre() {
fill(sumleft + 1, sumleft + n + 1, (long long)myINF);
fill(sumright + 1, sumright + n + 1, (long long)myINF);
}
void goright() {
dpr[MAX_N - 1] = n * myINF;
for (long long i = MAX_N - 2; i >= 1; i--) {
dpr[i] = dpr[i + 1];
for (long long j = 0; j < cntsl[i].size(); j++) {
long long num = cntsl[i][j].first, pr = cntsl[i][j].second,
prev = sumright[num];
sumright[num] = min(prev, pr), dpr[i] = dpr[i] - prev + sumright[num];
}
}
}
void goleft() {
dpl[0] = n * myINF;
for (long long i = 1; i < MAX_N; i++) {
dpl[i] = dpl[i - 1];
for (long long j = 0; j < cntsr[i].size(); j++) {
long long num = cntsr[i][j].first, pr = cntsr[i][j].second,
prev = sumleft[num];
sumleft[num] = min(prev, pr), dpl[i] = dpl[i] - prev + sumleft[num];
}
}
}
long long get_ans() {
long long ans = 1e18;
for (long long i = 0; i < MAX_N - k - 1; i++)
ans = min(ans, dpr[i + k + 1] + dpl[i]);
return (ans >= myINF) ? -1 : ans;
}
void solve() {
goright();
goleft();
cout << get_ans();
}
int main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cout << fixed << setprecision(0);
inp();
pre();
solve();
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
const int N = 200005;
using namespace std;
long long read() {
long long x = 0, f = 1;
char c;
do {
c = getchar();
if (c == '-') f = -1;
} while (c < '0' || c > '9');
while ('0' <= c && c <= '9')
x = (x << 3) + (x << 1) + (c ^ 48), c = getchar();
return x * f;
}
int i, l, r, mid, n, m, k, num;
long long sum, vis[N], f[N], g[N], ans;
struct node {
long long d, f, t, c;
} z[N];
bool cmp(node x, node y) { return x.d < y.d; }
int main() {
n = read();
m = read();
k = read();
for (i = 1; i <= m; i++)
z[i].d = read(), z[i].f = read(), z[i].t = read(), z[i].c = read();
sort(z + 1, z + m + 1, cmp);
for (i = 1; i <= m; i++) {
if (z[i].f) {
sum -= vis[z[i].f];
if (!vis[z[i].f]) num++, vis[z[i].f] = z[i].c;
vis[z[i].f] = min(vis[z[i].f], z[i].c);
sum += vis[z[i].f];
}
if (num == n)
f[i] = sum;
else
f[i] = -1;
}
memset(vis, 0, sizeof(vis));
num = sum = 0;
for (i = m; i; i--) {
if (z[i].t) {
sum -= vis[z[i].t];
if (!vis[z[i].t]) num++, vis[z[i].t] = z[i].c;
vis[z[i].t] = min(vis[z[i].t], z[i].c);
sum += vis[z[i].t];
}
if (num == n)
g[i] = sum;
else
g[i] = -1;
}
ans = -1;
for (i = 1; i <= m; i++) {
if (f[i] == -1) continue;
l = i + 1, r = m;
while (l < r) {
mid = (l + r) >> 1;
if (z[mid].d <= z[i].d + k)
l = mid + 1;
else
r = mid;
}
if (z[l].d <= z[i].d + k) continue;
if (l > m || g[l] == -1) continue;
if (ans == -1)
ans = f[i] + g[l];
else
ans = min(ans, f[i] + g[l]);
}
printf("%I64d", ans);
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 69;
const long long INF = 1e18;
struct item {
long long d, fr, to, c;
};
bool cmp(item a, item b) { return a.d < b.d; }
item a[MAXN];
long long pr[MAXN], suf[MAXN];
long long go[MAXN];
long long n, m, k;
int main() {
cin >> n >> m >> k;
for (long long i = 0; i < m; ++i)
cin >> a[i].d >> a[i].fr >> a[i].to >> a[i].c;
sort(a, a + m, cmp);
for (long long i = 1; i <= n; ++i) go[i] = INF;
long long ans = 0;
long long cnt = 0;
for (long long i = 0; i < m; ++i) {
if (a[i].fr == 0) {
if (i == 0)
pr[i] = INF;
else
pr[i] = pr[i - 1];
continue;
}
long long fr = a[i].fr, to = a[i].to, d = a[i].d, c = a[i].c;
if (go[fr] == INF) {
ans += c;
go[fr] = c;
cnt++;
} else if (c < go[fr]) {
ans -= go[fr];
go[fr] = c;
ans += go[fr];
}
if (cnt == n)
pr[i] = ans;
else
pr[i] = INF;
}
ans = 0;
for (long long i = 1; i <= n; ++i) go[i] = INF;
cnt = 0;
for (long long i = m - 1; i >= 0; --i) {
if (a[i].to == 0) {
suf[i] = INF;
if (i == m - 1)
suf[i] = INF;
else
suf[i] = suf[i + 1];
continue;
}
long long fr = a[i].fr, to = a[i].to, d = a[i].d, c = a[i].c;
if (go[to] == INF) {
ans += c;
go[to] = c;
cnt++;
} else if (c < go[to]) {
ans -= go[to];
go[to] = c;
ans += go[to];
}
if (cnt == n)
suf[i] = ans;
else
suf[i] = INF;
}
long long res = INF;
for (long long i = 0; i < m; ++i) {
long long out = a[i].d + k + 1;
long long l = -1, r = m;
while (l + 1 < r) {
long long mi = (l + r) / 2;
if (a[mi].d >= out)
r = mi;
else
l = mi;
}
if (r == m) continue;
if (pr[i] != INF && suf[r] != INF) res = min(res, pr[i] + suf[r]);
}
if (res == INF)
cout << -1;
else
cout << res;
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int gcd(int a, int b) {
if (a == 0) return b;
return gcd(b % a, a);
}
vector<vector<pair<int, int> > > dict;
vector<pair<int, pair<int, int> > > arr, depart;
vector<int> best;
long long totdep[1000050], totarr[1000050];
int main() {
int n, m, k;
int mxDay = 0;
scanf("%d%d%d", &n, &m, &k);
dict.resize(n + 1);
best.resize(n + 1);
int count = 0;
int a, b, c, d;
for (int i = 0; i < m; ++i) {
scanf("%d%d%d%d", &a, &b, &c, &d);
if (c == 0)
depart.push_back(make_pair(a, make_pair(b, d)));
else
arr.push_back(make_pair(a, make_pair(c, d)));
mxDay = max(mxDay, a);
}
sort(arr.rbegin(), arr.rend());
sort(depart.begin(), depart.end());
long long res = 0;
for (int i = 0; i < depart.size(); ++i) {
int day = depart[i].first;
int city = depart[i].second.first;
int cost = depart[i].second.second;
if (best[city] == 0) {
count++;
best[city] = cost;
res += best[city];
} else {
res = res - best[city];
best[city] = min(best[city], cost);
res += best[city];
}
if (count == n) totdep[day] = res;
}
count = 0;
res = 0;
best.clear();
best.resize(n + 1);
for (int i = 0; i < arr.size(); ++i) {
int day = arr[i].first;
int city = arr[i].second.first;
int cost = arr[i].second.second;
if (best[city] == 0) {
count++;
best[city] = cost;
res += best[city];
} else {
res = res - best[city];
best[city] = min(best[city], cost);
res += best[city];
}
if (count == n) totarr[day] = res;
}
for (int i = 1; i <= mxDay; ++i)
if (totdep[i] == 0)
totdep[i] = totdep[i - 1];
else if (totdep[i - 1] != 0)
totdep[i] = min(totdep[i], totdep[i - 1]);
for (int i = mxDay; i >= 1; --i) {
if (totarr[i] == 0)
totarr[i] = totarr[i + 1];
else if (totarr[i + 1] != 0)
totarr[i] = min(totarr[i], totarr[i + 1]);
}
long long ans = 1000000000000000;
for (int i = 1; i <= mxDay; ++i) {
if (totdep[i] != 0 && i + k + 1 <= mxDay && totarr[i + k + 1] != 0) {
ans = min(ans, totdep[i] + totarr[i + k + 1]);
}
}
if (ans == 1000000000000000)
cout << -1 << endl;
else
cout << ans << endl;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
template <typename Arg1>
void __f(const char* name, Arg1&& arg1) {
cerr << name << " : " << arg1 << std::endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args) {
const char* comma = strchr(names + 1, ',');
cerr.write(names, comma - names) << " : " << arg1 << " | ";
__f(comma + 1, args...);
}
long long modpow(long long a, long long n) {
long long ret = 1;
long long b = a;
while (n) {
if (n & 1) ret = (ret * b) % 1000000007ll;
b = (b * b) % 1000000007ll;
n >>= 1;
}
return (long long)ret;
}
const int maxn = 1000005;
const long long INF = 1e15;
vector<pair<int, int> > incoming[maxn], outgoing[maxn];
long long pre[maxn], suf[maxn], cur[maxn];
int main() {
int n, m, k;
cin >> n >> m >> k;
int maxdays = 0;
for (int i = 0; i < (int)m; i++) {
int d, u, v, c;
cin >> d >> u >> v >> c;
if (v == 0) {
incoming[d].push_back({u, c});
} else
outgoing[d].push_back({v, c});
maxdays = max(maxdays, d);
}
for (int i = 0; i < (int)maxn; i++) cur[i] = -1;
long long curcost = 0;
int covered = 0;
for (int i = 0; i < (int)maxn; i++) {
for (auto it : incoming[i]) {
int u = it.first;
int cost = it.second;
if (cur[u] == -1) {
curcost += cost;
cur[u] = cost;
covered++;
} else if (cur[u] > cost) {
curcost -= cur[u];
cur[u] = cost;
curcost += cur[u];
}
}
if (covered == n)
pre[i] = curcost;
else
pre[i] = INF;
}
for (int i = 0; i < (int)maxn; i++) cur[i] = -1;
curcost = 0;
covered = 0;
for (int i = maxn - 1; i >= 1; i--) {
for (auto it : outgoing[i]) {
int u = it.first;
int cost = it.second;
if (cur[u] == -1) {
curcost += cost;
cur[u] = cost;
covered++;
} else if (cur[u] > cost) {
curcost -= cur[u];
cur[u] = cost;
curcost += cur[u];
}
}
if (covered == n)
suf[i] = curcost;
else
suf[i] = INF;
}
long long res = INF;
for (int i = 1; i <= maxdays; i++)
if (i + k + 1 <= maxdays) res = min(res, pre[i] + suf[i + k + 1]);
if (res >= INF) res = -1;
cout << res << endl;
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1000000 + 10;
const long long INF = 200000000000LL;
int n, m, k;
vector<pair<int, int> > in[maxn], out[maxn];
long long pre[maxn], suf[maxn];
long long minc[100000 + 10];
int main() {
scanf("%d%d%d", &n, &m, &k);
int maxd = 1;
for (int i = 0; i < m; i++) {
int d, f, t, c;
scanf("%d%d%d%d", &d, &f, &t, &c);
if (!f)
out[d].push_back(make_pair(t, c));
else
in[d].push_back(make_pair(f, c));
if (d > maxd) maxd = d;
}
for (int i = 1; i < n + 1; i++) minc[i] = INF;
long long tot = INF * n;
for (int i = 1; i < maxd + 1; i++) {
for (pair<int, int> x : in[i]) {
if (x.second < minc[x.first]) {
tot -= minc[x.first] - x.second;
minc[x.first] = x.second;
}
}
pre[i] = tot;
}
for (int i = 1; i < n + 1; i++) minc[i] = INF;
tot = INF * n;
for (int i = maxd + 1 - 1; i >= 1; i--) {
for (pair<int, int> x : out[i]) {
if (x.second < minc[x.first]) {
tot -= minc[x.first] - x.second;
minc[x.first] = x.second;
}
}
suf[i] = tot;
}
long long ans = INF * n;
for (int i = 1; i + k + 1 <= maxd; i++) {
ans = min(ans, pre[i] + suf[i + k + 1]);
}
if (ans >= INF)
printf("-1\n");
else
printf("%lld\n", ans);
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
template <class P, class Q>
inline void smin(P &a, Q b) {
if (b < a) a = b;
}
template <class P, class Q>
inline void smax(P &a, Q b) {
if (a < b) a = b;
}
const long long inf = (long long)1e17;
const int maxd = 1000000 + 100;
const int maxn = 100000 + 100;
int n, m, k;
vector<pair<int, int> > fs[maxd], ts[maxd];
int cf[maxd];
long long mf[maxd];
int ct[maxd];
long long mt[maxd];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> n >> m >> k;
k++;
for (int i = 0, i__n = (int)(m); i < i__n; ++i) {
int d, f, t, c;
cin >> d >> f >> t >> c;
d--, f--, t--;
if (t == -1)
fs[d].push_back(pair<int, int>(f, c));
else
ts[d].push_back(pair<int, int>(t, c));
}
memset(cf, -1, sizeof cf);
int cntf = 0;
long long curf = 0;
for (int d = 0, d__n = (int)(maxd); d < d__n; ++d) {
for (pair<int, int> p : fs[d])
if (cf[p.first] == -1)
cntf++, cf[p.first] = p.second, curf += cf[p.first];
else
curf -= cf[p.first], smin(cf[p.first], p.second), curf += cf[p.first];
if (cntf == n)
mf[d] = curf;
else
mf[d] = inf;
}
memset(ct, -1, sizeof ct);
int cntt = 0;
long long curt = 0;
for (int d = (int)(maxd), d__a = (int)(0); d-- > d__a;) {
for (pair<int, int> p : ts[d])
if (ct[p.first] == -1)
cntt++, ct[p.first] = p.second, curt += ct[p.first];
else
curt -= ct[p.first], smin(ct[p.first], p.second), curt += ct[p.first];
if (cntt == n)
mt[d] = curt;
else
mt[d] = inf;
}
long long ans = inf;
for (int d = 0, d__n = (int)(maxd - k); d < d__n; ++d)
smin(ans, mf[d] + mt[d + k]);
cout << (ans == inf ? -1 : ans) << endl;
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
long long occp[1000010], occs[1000010], sizep[1000010], sizes[1000010],
costp[1000010], costs[1000010];
struct flight {
long long cost, dep, dest;
flight(long long a = 0, long long b = 0, long long c = 0) {
cost = a;
dep = b;
dest = c;
}
};
vector<flight> arrive[1000010], reach[1000010];
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
memset(occp, -1, sizeof(occp));
memset(occs, -1, sizeof(occs));
long long n, m, k;
cin >> n >> m >> k;
for (long long i = 0; i < m; i++) {
long long a, b, c, d;
cin >> a >> b >> c >> d;
if (c == 0) {
arrive[a].push_back(flight(d, b, c));
} else {
reach[a].push_back(flight(d, b, c));
}
}
for (long long i = 1; i < 1000010; i++) {
sizep[i] = sizep[i - 1];
costp[i] = costp[i - 1];
if (arrive[i].size()) {
for (long long j = 0; j < arrive[i].size(); j++) {
if (occp[arrive[i][j].dep] == -1) {
sizep[i] += 1;
occp[arrive[i][j].dep] = arrive[i][j].cost;
costp[i] += arrive[i][j].cost;
} else if (occp[arrive[i][j].dep] > arrive[i][j].cost) {
costp[i] -= occp[arrive[i][j].dep];
costp[i] += arrive[i][j].cost;
occp[arrive[i][j].dep] = arrive[i][j].cost;
}
}
}
}
for (long long i = 1000010 - 2; i >= 1; i--) {
sizes[i] = sizes[i + 1];
costs[i] = costs[i + 1];
if (reach[i].size()) {
for (long long j = 0; j < reach[i].size(); j++) {
if (occs[reach[i][j].dest] == -1) {
sizes[i] += 1;
occs[reach[i][j].dest] = reach[i][j].cost;
costs[i] += reach[i][j].cost;
} else if (occs[reach[i][j].dest] > reach[i][j].cost) {
costs[i] -= occs[reach[i][j].dest];
costs[i] += reach[i][j].cost;
occs[reach[i][j].dest] = reach[i][j].cost;
}
}
}
}
long long mini = 2000000000000000000;
long long low = 1, high = k;
while (high < 1000010 - 2) {
if (sizep[low - 1] == n && sizes[high + 1] == n) {
mini = min(mini, costp[low - 1] + costs[high + 1]);
}
low++;
high++;
}
if (mini == 2000000000000000000)
cout << -1 << '\n';
else
cout << mini << '\n';
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
using namespace std;
const long long nDays = 1000005;
int main() {
cin.sync_with_stdio(0);
long long n, m, k;
cin >> n >> m >> k;
vector<vector<pair<long long, long long> > > from(nDays);
vector<vector<pair<long long, long long> > > to(nDays);
for (long long i = 0; i < (m); i++) {
long long d, f, t, c;
cin >> d >> f >> t >> c;
if (f == 0) {
from[d - 1].push_back(pair<long long, long long>({t - 1, c}));
} else {
to[d - 1].push_back(pair<long long, long long>({f - 1, c}));
}
}
vector<long long> prefs(nDays);
{
vector<long long> costs(n, 9999999999999ll);
long long currSum = n * 9999999999999ll;
for (long long i = 0; i < (nDays); i++) {
for (long long j = 0; j < (((long long)(to[i]).size())); j++) {
currSum -= costs[to[i][j].first];
costs[to[i][j].first] = min(to[i][j].second, costs[to[i][j].first]);
currSum += costs[to[i][j].first];
}
prefs[i] = currSum;
}
}
vector<long long> suffs(nDays);
{
vector<long long> costs(n, 9999999999999ll);
long long currSum = n * 9999999999999ll;
for (long long i = (nDays - 1); i >= (0); i--) {
for (long long j = 0; j < (((long long)(from[i]).size())); j++) {
currSum -= costs[from[i][j].first];
costs[from[i][j].first] =
min(from[i][j].second, costs[from[i][j].first]);
currSum += costs[from[i][j].first];
}
suffs[i] = currSum;
}
}
long long minPrice = 9999999999999ll;
for (long long i = 0; i < (nDays); i++) {
if (i + k + 1 >= nDays) continue;
minPrice = min(minPrice, prefs[i] + suffs[i + k + 1]);
}
if (minPrice == 9999999999999ll)
cout << "-1\n";
else
cout << minPrice << "\n";
return 0;
}
| CPP |
854_D. Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
long long int MOD = 1000000007;
long long int powe(long long int a, long long int b) {
long long int x = 1, y = a;
while (b > 0) {
if (b % 2 == 1) {
x = (x * y);
x %= MOD;
}
y = (y * y);
y %= MOD;
b /= 2;
}
return x;
}
long long int InverseEuler(long long int n) { return powe(n, MOD - 2); }
long long int b[1000110];
long long int f[1000110];
vector<pair<int, int> > frm[1000010];
vector<pair<int, int> > to[1000010];
long long int infl = 1e18;
long long int mib[1000110];
long long int mif[1000110];
int has[500010];
int main() {
int n;
int k;
cin >> n;
for (int i = 0; i <= 1000010; i++) {
b[i] = infl;
f[i] = infl;
mif[i] = infl;
mib[i] = infl;
}
int m;
cin >> m;
cin >> k;
vector<pair<pair<pair<int, int>, int>, int> > v;
for (int i = 0; i < m; i++) {
int x, y, z, c;
cin >> x >> y >> z >> c;
v.push_back(make_pair(make_pair(make_pair(x, y), z), c));
if (y == 0)
to[x].push_back(make_pair(z, c));
else
frm[x].push_back(make_pair(y, c));
}
sort(v.begin(), v.end());
reverse(v.begin(), v.end());
int c = 0;
long long int ans = 0;
memset(has, -1, sizeof(has));
for (unsigned int i = 1000000; i >= 1; i--) {
unsigned int sz = to[i].size();
for (unsigned int k = 0; k < sz; k++) {
int tocity = to[i][k].first;
int tocost = to[i][k].second;
if (has[tocity] == -1) {
ans += tocost;
has[tocity] = tocost;
c++;
} else {
if (has[tocity] > tocost) {
ans -= has[tocity];
has[tocity] = tocost;
ans += has[tocity];
}
}
if (c == n) {
b[i] = min(b[i], ans);
}
}
}
long long int ret = infl;
memset(has, -1, sizeof(has));
ans = 0;
c = 0;
for (unsigned int i = 1; i <= 1000000; i++) {
unsigned int sz = frm[i].size();
for (unsigned int k = 0; k < sz; k++) {
int frmcity = frm[i][k].first;
int tocost = frm[i][k].second;
if (has[frmcity] == -1) {
ans += tocost;
has[frmcity] = tocost;
c++;
} else {
if (has[frmcity] > tocost) {
ans -= has[frmcity];
has[frmcity] = tocost;
ans += has[frmcity];
}
}
if (c == n) {
f[i] = min(f[i], ans);
}
}
}
for (int i = 1; i <= 1000000; i++) mif[i] = min(mif[i - 1], f[i]);
mib[1000001] = infl;
for (int i = 1000000; i >= 1; i--) mib[i] = min(mib[i + 1], b[i]);
for (int i = 1; i <= 1000000; i++) {
int e = i + k - 1;
if (e <= 1000000) {
if (mif[i - 1] != infl && mib[e + 1] != infl)
ret = min(ret, mif[i - 1] + mib[e + 1]);
}
}
if (ret >= infl) ret = -1;
cout << ret << endl;
return 0;
}
| CPP |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.