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 | import java.io.*;
import java.text.*;
import java.util.*;
public class D {
public static void main(String[] args) throws Exception {
new D().run();
}
public void run() throws Exception {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(f.readLine());
int n = Integer.parseInt(st.nextToken()), m = Integer.parseInt(st.nextToken()), k = Integer.parseInt(st.nextToken())+1;
if(m < n * 2) {
System.out.println(-1);
return;
}
PriorityQueue<Flight> arrive = new PriorityQueue<Flight>();
ArrayList<Flight>[] depart = (ArrayList<Flight>[])new ArrayList[n];
for(int i = 0; i < n; i++) depart[i] = new ArrayList<Flight>();
for(int i =0 ; i < m; i++) {
Flight fl = new Flight(f.readLine());
if(fl.to)
arrive.add(fl);
else {
depart[fl.city].add(fl);
continue;
}
}
int[][] min = new int[n][];
int[][] mind = new int[n][];
//checking if return is possible
for(int i = 0; i < n; i++) {
ArrayList<Flight> a = depart[i];
if(a.isEmpty()) {
System.out.println(-1);
return;
}
Collections.sort(a);
min[i] = new int[a.size()];
mind[i] = new int[a.size()];
min[i][a.size()-1] = a.get(a.size()-1).cost;
mind[i][a.size()-1] = a.size()-1;
for(int j = a.size()-2; j >= 0; j--) {
if(a.get(j).cost < min[i][j+1]) {
min[i][j] = a.get(j).cost;
mind[i][j] = j;
} else {
min[i][j] = min[i][j+1];
mind[i][j] = mind[i][j+1];
}
}
}
int[] costs = new int[n];
int cnt = 0;
int time = 0;
long sum = 0;
Arrays.fill(costs, -1);
while(cnt != n && !arrive.isEmpty()) {
Flight fl = arrive.poll();
if(costs[fl.city] == -1) {
cnt++;
sum += costs[fl.city] = fl.cost;
time = fl.t;
} else {
sum -= costs[fl.city];
costs[fl.city] = Math.min(costs[fl.city], fl.cost);
sum += costs[fl.city];
}
}
if(cnt != n) {
System.out.println(-1);
return;
}
long best = sum;
int[] departind = new int[n];
for(int i = 0; i < n; i++) {
int index = binsearch(depart[i],time+k);
if(index == -1) {
//System.out.println(i + " does not have valid return");
//System.out.println(depart[i] + " " + (time+k));
System.out.println(-1);
return;
}
best += min[i][index];
departind[i] = mind[i][index];
}
while(!arrive.isEmpty()) {
Flight fl = arrive.poll();
int curcost = fl.cost;
int depindex = binsearch(depart[fl.city],fl);
if(depindex == -1 || depindex == depart[fl.city].size()) continue;
curcost += min[fl.city][depindex];
if(curcost < costs[fl.city] + depart[fl.city].get(departind[fl.city]).cost) {
departind[fl.city] = depindex;
sum -= costs[fl.city];
sum += fl.cost;
costs[fl.city] = fl.cost;
time = fl.t;
long curbest = sum;
for(int i = 0; i < n; i++) {
int index = binsearch(depart[i],time+k);
if(index == -1 || index == depart[i].size()) {
System.out.println(best);
return;
}
while(index != depart[i].size() && depart[i].get(index).t < time+k) index++;
if(index == -1 || index == depart[i].size()) {
System.out.println(best);
return;
}
//System.out.println(i + " best dep: " + index);
curbest += min[i][index];
departind[i] = mind[i][index];
}
//System.out.println();
if(curbest < best) best = curbest;
}
}
System.out.println(best);
}
//approach: store flights back home and iterate over arrival flights in order.
//if you come across a flight that has the latest arrival < k then stop and print
//the best so far (theres no more compatible flights). otherwise, bin search for
//the earliest departure time and find min cost.
public int binsearch(ArrayList<Flight> a, Flight i) {
int l = 0, h = a.size();
while(l != h) {
int m = (l+h)/2;
if(i.compareTo(a.get(m)) > 0) l = m+1;
else if(i.compareTo(a.get(m)) < 0) h = m;
else return m;
}
return l;
}public int binsearch(ArrayList<Flight> a, int i) {
int l = 0, h = a.size();
while(l != h) {
int m = (l+h)/2;
if(i >(a.get(m)).t) l = m+1;
else if(i < (a.get(m)).t) h = m;
else return m;
}
if(l == a.size()) return -1;
return l;
}
class Flight implements Comparable<Flight> {
int t, city, cost;
boolean to;
public Flight(String s) {
StringTokenizer st = new StringTokenizer(s);
t = Integer.parseInt(st.nextToken());
String next = st.nextToken();
if(next.equals("0")) {
to = false;
city = Integer.parseInt(st.nextToken())-1;
} else {
to = true;
city = Integer.parseInt(next)-1;
st.nextToken();
}
cost = Integer.parseInt(st.nextToken());
}
public int compareTo(Flight f) {
return t - f.t;
}
public String toString() {
return t + " " + city + " " + 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 maxn = 1e6 + 10;
const long long inf = 1e15;
int n, m, k;
struct flight {
int pos, cost;
};
long long g1[maxn], g2[maxn], sum1[maxn], sum2[maxn];
vector<flight> G1[maxn], G2[maxn];
int f[maxn];
template <class T>
void read(T &x) {
x = 0;
char c = getchar();
while (!isdigit(c)) c = getchar();
while (isdigit(c)) x = (x << 1) + (x << 3) + (c ^ 48), c = getchar();
}
int main() {
int d, u, v, c, Maxday = 0;
read(n), read(m), read(k);
for (int i = (1); i <= (int)(m); ++i) {
read(d), read(u), read(v), read(c);
if (v == 0)
G1[d].push_back((flight){u, c});
else
G2[d].push_back((flight){v, c});
Maxday = max(d, Maxday);
}
sum1[0] = sum2[Maxday + 1] = inf;
int cnt = 0;
long long res = 0;
for (int i = (1); i <= (int)(Maxday); ++i) {
if (!G1[i].size())
sum1[i] = sum1[i - 1];
else {
for (int j = (0); j <= (int)(G1[i].size() - 1); ++j) {
u = G1[i][j].pos, c = G1[i][j].cost;
if (cnt < n) {
if (g1[u]) {
if (c < g1[u]) res += c - g1[u], g1[u] = c;
} else
g1[u] = c, res += c, ++cnt;
if (cnt == n)
sum1[i] = res;
else
sum1[i] = inf;
} else {
sum1[i] = res;
if (c < g1[u]) sum1[i] += c - g1[u], g1[u] = c;
res = sum1[i];
}
}
}
}
cnt = 0, res = 0;
for (int i = (Maxday); i >= (int)(1); --i) {
if (!G2[i].size())
sum2[i] = sum2[i + 1];
else {
for (int j = (0); j <= (int)(G2[i].size() - 1); ++j) {
u = G2[i][j].pos, c = G2[i][j].cost;
if (cnt < n) {
if (g2[u]) {
if (c < g2[u]) res += c - g2[u], g2[u] = c;
} else
g2[u] = c, res += c, ++cnt;
if (cnt == n)
sum2[i] = res;
else
sum2[i] = inf;
} else {
sum2[i] = res;
if (c < g2[u]) sum2[i] += c - g2[u], g2[u] = c;
res = sum2[i];
}
}
}
}
long long ans = inf;
for (int i = (1); i <= (int)(Maxday - k - 1); ++i)
ans = min(ans, sum1[i] + sum2[i + k + 1]);
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;
const int maxn = 1000000 + 9;
struct Node {
int x, d, c;
Node(int _x, int _d, int _c) : x(_x), d(_d), c(_c) {}
bool operator<(const Node &o) const { return d < o.d; }
};
int N, K;
long long mnf[maxn], mnt[maxn];
vector<Node> from, to;
int F[maxn];
void Init() {
int m, d, f, t, c;
cin >> N >> m >> K;
for (int i = 0; i < m; i++) {
scanf("%d%d%d%d", &d, &f, &t, &c);
if (f == 0) {
to.push_back(Node(t, d, c));
} else {
from.push_back(Node(f, d, c));
}
}
}
bool cmp(const Node &l, const Node &r) { return l.d > r.d; }
int main() {
Init();
sort(from.begin(), from.end());
sort(to.begin(), to.end(), cmp);
for (int i = 1; i <= N; i++) {
F[i] = 0;
}
memset(mnf, -1, sizeof mnf);
int cnt = 0, day = 0;
long long cost = 0;
for (vector<Node>::iterator I = from.begin(); I != from.end(); I++) {
day = max(day, I->d);
if (!F[I->x]) {
cnt++;
cost += (F[I->x] = I->c);
} else if (I->c < F[I->x]) {
cost -= F[I->x] - I->c;
F[I->x] = I->c;
}
if (cnt == N) {
mnf[day] = cost;
}
}
for (int i = 2; i <= 1000000; i++)
if (~mnf[i - 1]) {
if (~mnf[i]) {
mnf[i] = min(mnf[i], mnf[i - 1]);
} else {
mnf[i] = mnf[i - 1];
}
}
for (int i = 1; i <= N; i++) {
F[i] = 0;
}
memset(mnt, -1, sizeof mnt);
cnt = 0, day = 1 << 30;
cost = 0;
for (vector<Node>::iterator I = to.begin(); I != to.end(); I++) {
day = min(day, I->d);
if (!F[I->x]) {
cnt++;
cost += (F[I->x] = I->c);
} else if (I->c < F[I->x]) {
cost -= F[I->x] - I->c;
F[I->x] = I->c;
}
if (cnt == N) {
mnt[day] = cost;
}
}
for (int i = 999999; i >= 1; i--)
if (~mnt[i + 1]) {
if (~mnt[i]) {
mnt[i] = min(mnt[i], mnt[i + 1]);
} else {
mnt[i] = mnt[i + 1];
}
}
long long ans = 1LL << 60;
for (int i = 1; i + K + 1 <= 1000000; i++)
if (~mnf[i] && ~mnt[i + K + 1]) {
ans = min(ans, mnf[i] + mnt[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 | #include <bits/stdc++.h>
using namespace std;
inline void read(int &x) {
char ch;
bool flag = false;
for (ch = getchar(); !isdigit(ch); ch = getchar())
if (ch == '-') flag = true;
for (x = 0; isdigit(ch); x = x * 10 + ch - '0', ch = getchar())
;
x = flag ? -x : x;
}
inline void read(long long &x) {
char ch;
bool flag = false;
for (ch = getchar(); !isdigit(ch); ch = getchar())
if (ch == '-') flag = true;
for (x = 0; isdigit(ch); x = x * 10 + ch - '0', ch = getchar())
;
x = flag ? -x : x;
}
int const maxn = 120000;
long long n, m, k;
struct zy {
long long day, x, cost;
} A[maxn], B[maxn];
int totA, totB;
struct kkk {
long long day, cost;
};
bool cmp(zy A, zy B) { return A.day < B.day; }
struct kkkkk {
deque<kkk> a;
int l = 0, r = -1;
void push(kkk x) {
while ((!a.empty()) && (x.cost <= a.back().cost)) a.pop_back();
a.push_back(x);
}
long long pop(long long lim) {
long long tmp = (*a.begin()).cost;
while ((!a.empty()) && ((*a.begin()).day < lim)) a.pop_front();
if (a.empty()) return -1;
return (*a.begin()).cost - tmp;
}
long long top() { return (*a.begin()).cost; }
bool Empty() { return a.empty(); }
} leave[maxn];
long long Min[maxn];
bool vis[maxn];
int main() {
read(n);
read(m);
read(k);
for (int i = 1; i <= m; i++) {
long long a, b, c, d;
read(a);
read(b);
read(c);
read(d);
zy tmp;
tmp.day = a;
tmp.x = b + c;
tmp.cost = d;
if (c == 0)
A[++totA] = tmp;
else
B[++totB] = tmp;
}
sort(A + 1, A + 1 + totA, cmp);
sort(B + 1, B + 1 + totB, cmp);
int cnt = 0;
int stA = 0;
memset(Min, 63, sizeof(Min));
for (int i = 1; i <= totA; i++) {
Min[A[i].x] = min(Min[A[i].x], A[i].cost);
if (!vis[A[i].x]) {
vis[A[i].x] = 1;
cnt++;
if (cnt == n) {
stA = i;
break;
}
}
}
if (cnt != n) {
puts("-1");
return 0;
}
int stB = 0;
for (int i = 1; i <= totB; i++)
if (B[i].day >= A[stA].day + k + 1) {
stB = i;
break;
}
for (int i = stB; i <= totB; i++)
if (B[i].day >= A[stA].day + k + 1) {
kkk tmp;
tmp.cost = B[i].cost;
tmp.day = B[i].day;
leave[B[i].x].push(tmp);
}
long long sum = 0;
for (int i = 1; i <= n; i++) {
if (leave[i].Empty()) {
puts("-1");
return 0;
}
sum = sum + Min[i] + leave[i].top();
}
long long ans = sum;
for (int i = 1; i <= totA; i++) {
int r = i - 1;
while ((r < totA) && (A[r + 1].day == A[i].day)) {
r++;
if (Min[A[r].x] > A[r].cost) {
sum += A[r].cost - Min[A[r].x];
Min[A[r].x] = A[r].cost;
}
}
i = r;
while ((stB <= totB) && (B[stB].day < A[i].day + k + 1)) {
long long tmp = leave[B[stB].x].pop(A[i].day + k + 1);
if (leave[B[stB].x].Empty()) break;
sum += tmp;
stB++;
}
if (leave[B[stB].x].Empty()) break;
ans = min(ans, sum);
}
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 MAXN = 1e5 + 10;
const int MAXD = 1e6 + 10;
const long long INF = 1e16;
struct e {
int p, c, id;
};
int Bin[MAXN], BinV[MAXN];
int Bout[MAXN];
int N, M, K, mxD = 0, cnt = 0;
priority_queue<pair<int, pair<int, int> > > to[MAXN];
vector<e> Fout[MAXD], Fin[MAXD];
bool possible = true, done = false;
long long ans = INF, cur = 0;
int main() {
scanf("%d", &N), scanf("%d", &M), scanf("%d", &K);
for (int i = 0; i < (int)M; i++) {
int d, first, t, c;
scanf("%d", &d), scanf("%d", &first), scanf("%d", &t), scanf("%d", &c);
if (first == 0 && d >= K) {
to[t].push({-c, {d, i}});
Fin[d].push_back({t, c, i});
} else if (t == 0)
Fout[d].push_back({first, c, i});
mxD = max(mxD, d);
}
for (int i = 1; i < (int)N + 1; i++) {
if (!to[i].empty()) {
Bin[i] = to[i].top().second.second;
BinV[i] = -to[i].top().first;
cur += BinV[i];
} else {
printf("-1\n");
return 0;
}
}
memset(Bout, -1, sizeof(Bout));
for (int d = 0; d < (int)mxD + 1; d++) {
if (d + K - 1 <= mxD)
for (int i = 0; i < (int)Fin[d + K - 1].size(); i++) {
int p = Fin[d + K - 1][i].p;
int c = Fin[d + K - 1][i].c;
int id = Fin[d + K - 1][i].id;
if (id == Bin[p]) {
while (!to[p].empty() && to[p].top().second.first <= d + K - 1)
to[p].pop();
if (!to[p].empty()) {
cur -= BinV[p];
BinV[p] = -to[p].top().first;
Bin[p] = to[p].top().second.second;
cur += BinV[p];
} else {
done = true;
break;
}
}
}
if (done) break;
if (cnt == N) {
ans = min(ans, cur);
}
for (int i = 0; i < (int)Fout[d].size(); i++) {
int p = Fout[d][i].p;
int c = Fout[d][i].c;
int id = Fout[d][i].id;
if (Bout[p] == -1) {
Bout[p] = c;
cur += c;
cnt++;
} else if (c < Bout[p]) {
cur -= Bout[p];
Bout[p] = c;
cur += Bout[p];
}
}
}
if (!possible)
printf("-1\n");
else
printf("%lld\n", ans == INF ? -1 : 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 | import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Map;
import java.util.TreeMap;
public class D {
public static void main(String[] args) {
FastScannerD sc = new FastScannerD(System.in);
int N = sc.nextInt(); //N + 1 cities
int M = sc.nextInt(); //num of flights
int K = sc.nextInt(); //len of olympiad
Flight[] arr = new Flight[M];
for(int i = 0; i<M; i++){
int d = sc.nextInt();
int f = sc.nextInt();
int t = sc.nextInt();
int c = sc.nextInt();
arr[i] = new Flight(d, f, t, c);
}
Arrays.sort(arr);
int[] cities = new int[N + 1];
int total_count = 0;
long cost_sums = 0;
int L = -1;
TreeMap<Integer, Long> costs_by_day_1 = new TreeMap<>();
for(Flight f : arr){
if(f.to != 0) continue;
if(cities[f.from] == 0){
cities[f.from] = f.cost;
cost_sums += f.cost;
total_count++;
if(total_count == N){
L = f.day;
costs_by_day_1.put(f.day, cost_sums);
}
}
else{
int old_cost = cities[f.from];
int new_cost = f.cost;
if(new_cost < old_cost){
cities[f.from] = f.cost;
cost_sums -= old_cost;
cost_sums += new_cost;
costs_by_day_1.put(f.day, cost_sums);
}
}
}
// System.out.println("L " + L);
// for(Map.Entry<Integer, Long> e : costs_by_day_1.entrySet()){
// System.out.println(e.getKey() + " " + e.getValue());
// }
cities = new int[N + 1];
total_count = 0;
cost_sums = 0;
int R = -1;
TreeMap<Integer, Long> costs_by_day_2 = new TreeMap<>();
for(int i = M-1; i >= 0; i--){
Flight f = arr[i];
if(f.from != 0) continue;
if(cities[f.to] == 0){
cities[f.to] = f.cost;
cost_sums += f.cost;
total_count++;
if(total_count == N){
R = f.day;
costs_by_day_2.put(f.day, cost_sums);
}
}
else{
int old_cost = cities[f.to];
int new_cost = f.cost;
if(new_cost < old_cost){
cities[f.to] = f.cost;
cost_sums -= old_cost;
cost_sums += new_cost;
costs_by_day_2.put(f.day, cost_sums);
}
}
}
// System.out.println("R " + R);
// for(Map.Entry<Integer, Long> e : costs_by_day_2.entrySet()){
// System.out.println(e.getKey() + " " + e.getValue());
// }
if(L == -1 || R == -1){
System.out.println(-1);
}
else if(L >= R){
System.out.println(-1);
}
else{
long cost = Long.MAX_VALUE;
boolean valid = false;
for(int i = L; i <= R; i++){
if((i+K+1) > R) break;
long left_cost = costs_by_day_1.floorEntry(i).getValue();
long right_cost = costs_by_day_2.ceilingEntry(i+K+1).getValue();
cost = Math.min(cost, left_cost + right_cost);
valid = true;
}
if(!valid) System.out.println(-1);
else System.out.println(cost);
}
}
}
class Flight implements Comparable<Flight>{
int day;
int from;
int to;
int cost;
Flight(int d, int f, int t, int c){
day = d;
from = f;
to = t;
cost = c;
}
@Override
public int compareTo(Flight f) {
return day - f.day;
}
}
class FastScannerD{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastScannerD(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 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 String next()
{
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 double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
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 {
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 c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isLineEndChar(int c)
{
if (filter != null)
return filter.isSpaceChar(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 | #include <bits/stdc++.h>
using namespace std;
template <class T1>
void deb(T1 e1) {
cout << e1 << endl;
}
template <class T1, class T2>
void deb(T1 e1, T2 e2) {
cout << e1 << " " << e2 << endl;
}
template <class T1, class T2, class T3>
void deb(T1 e1, T2 e2, T3 e3) {
cout << e1 << " " << e2 << " " << e3 << endl;
}
template <class T1, class T2, class T3, class T4>
void deb(T1 e1, T2 e2, T3 e3, T4 e4) {
cout << e1 << " " << e2 << " " << e3 << " " << e4 << endl;
}
template <class T1, class T2, class T3, class T4, class T5>
void deb(T1 e1, T2 e2, T3 e3, T4 e4, T5 e5) {
cout << e1 << " " << e2 << " " << e3 << " " << e4 << " " << e5 << endl;
}
template <class T1, class T2, class T3, class T4, class T5, class T6>
void deb(T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6) {
cout << e1 << " " << e2 << " " << e3 << " " << e4 << " " << e5 << " " << e6
<< endl;
}
const long long int mod = 10000000000007;
vector<pair<long long int, long long int> > adj1[1000005];
vector<pair<long long int, long long int> > adj2[1000005];
long long int come[1000005];
long long int bak[1000005];
long long int pre[1000005];
int main() {
int n, m, k;
scanf("%d %d %d", &n, &m, &k);
for (int i = 1; i <= m; i++) {
long long int u, v, d, c;
scanf("%lld %lld %lld %lld", &d, &u, &v, &c);
if (u == 0) {
adj2[d].push_back(make_pair(v, c));
} else {
adj1[d].push_back(make_pair(u, c));
}
}
for (int i = 1; i <= n; i++) {
pre[i] = mod;
come[0] += pre[i];
}
for (int i = 1; i < 1000005; i++) {
long long int now = come[i - 1];
for (int j = 0; j < adj1[i].size(); j++) {
int u = adj1[i][j].first;
long long int cost = adj1[i][j].second;
if (pre[u] > cost) {
now -= pre[u];
pre[u] = cost;
now += pre[u];
}
}
come[i] = now;
}
for (int i = 1; i <= n; i++) {
pre[i] = mod;
bak[1000005 - 1] += pre[i];
}
for (int i = 1000005 - 2; i >= 1; i--) {
long long int now = bak[i + 1];
for (int j = 0; j < adj2[i].size(); j++) {
int u = adj2[i][j].first;
long long int cost = adj2[i][j].second;
if (pre[u] > cost) {
now -= pre[u];
pre[u] = cost;
now += pre[u];
}
}
bak[i] = now;
}
long long int ans = mod * 100;
for (int i = 1; i + k < 1000005; i++) {
ans = min(ans, come[i - 1] + bak[i + k]);
}
if (ans >= mod) ans = -1;
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.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.util.*;
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(in, out);
out.close();
}
}
class Task {
// static int MAX = 1000001;
// List<List<Integer>> g = new ArrayList<>();
// int n;
// char[] s;
public void solve(Scanner in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
List<Tri> from = new ArrayList<>();
List<Tri> to = new ArrayList<>();
for (int i = 0; i < m; i++) {
int d = in.nextInt();
int f = in.nextInt() - 1;
int t = in.nextInt() - 1;
int c = in.nextInt();
if (t == -1) {
Tri v = new Tri(d, f, c);
from.add(v);
} else {
Tri v = new Tri(d, t, c);
to.add(v);
}
}
from.sort(Comparator.comparingInt(o -> o.a));
to.sort(Comparator.comparingInt((Tri o) -> o.a).reversed());
int[] min = new int[n];
int curDay = -1;
if (from.size() > 0) {
curDay = from.get(0).a;
}
Arrays.fill(min, -1);
List<Pair<Integer, Long>> mapFrom = new ArrayList<>();
// Map<Integer, Long> mapFrom = new HashMap<>();
boolean bb = false;
int counter = 0;
long total = 0;
for (Tri tri : from) {
if (tri.a != curDay) {
if (bb) {
mapFrom.add(new Pair<>(curDay, total));
}
curDay = tri.a;
}
if (min[tri.b] != -1) {
if (tri.c < min[tri.b]) {
total -= min[tri.b] - tri.c;
min[tri.b] = tri.c;
}
} else {
++counter;
min[tri.b] = tri.c;
if (counter == n) {
bb = true;
total = Arrays.stream(min).mapToLong(t -> t).sum();
}
}
}
if (bb) {
mapFrom.add(new Pair<>(curDay, total));
}
min = new int[n];
curDay = -1;
if (to.size() > 0) {
curDay = to.get(0).a;
}
Arrays.fill(min, -1);
List<Pair<Integer, Long>> mapTo = new ArrayList<>();
bb = false;
counter = 0;
total = 0;
for (Tri tri : to) {
if (tri.a != curDay) {
if (bb) {
mapTo.add(new Pair<>(curDay, total));
}
curDay = tri.a;
}
if (min[tri.b] != -1) {
if (tri.c < min[tri.b]) {
total -= min[tri.b] - tri.c;
min[tri.b] = tri.c;
}
} else {
++counter;
min[tri.b] = tri.c;
if (counter == n) {
bb = true;
total = Arrays.stream(min).mapToLong(t -> t).sum();
}
}
}
if (bb) {
mapTo.add(new Pair<>(curDay, total));
}
long res = Long.MAX_VALUE;
int p1 = 0;
int p2 = mapTo.size() - 1;
if (mapFrom.size() == 0 || mapTo.size() == 0) {
System.out.println(-1);
return;
}
while (p2 >= 0 && p1 < mapFrom.size()) {
Pair<Integer, Long> el1 = mapFrom.get(p1);
Pair<Integer, Long> el2 = mapTo.get(p2);
if (el2.a - el1.a - 1 >= k) {
res = Math.min(el1.b + el2.b, res);
p1++;
} else {
p2--;
}
}
if (res == Long.MAX_VALUE) {
System.out.println(-1);
} else {
System.out.println(res);
}
}
}
class Utils {
public static int binarySearch(int[] a, int key) {
int s = 0;
int f = a.length;
while (f > s) {
int mid = (s + f) / 2;
if (a[mid] > key) {
f = mid - 1;
} else if (a[mid] <= key) {
s = mid + 1;
}
}
return -1;
}
public static long gcd(long a, long b) {
return b != 0 ? gcd(b, a % b) : a;
}
public static long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
static List<Integer> prime(int number) {
List<Integer> a = new ArrayList<>();
for (int i = 2; i * i <= number; i++) {
if (number % i == 0) {
a.add(i);
number /= i;
i = 1;
}
}
a.add(number);
return a;
}
}
class Pair<T, U> {
public T a;
public U b;
public Pair(T a, U b) {
this.a = a;
this.b = b;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
if (a != null ? !a.equals(pair.a) : pair.a != null) return false;
return b != null ? b.equals(pair.b) : pair.b == null;
}
@Override
public int hashCode() {
int result = a != null ? a.hashCode() : 0;
result = 31 * result + (b != null ? b.hashCode() : 0);
return result;
}
}
class Vect {
public int a;
public int b;
public Vect(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Vect vect = (Vect) o;
if (a != vect.a) return false;
return b == vect.b;
}
@Override
public int hashCode() {
int result = a;
result = 31 * result + b;
return result;
}
}
class Tri {
public int a;
public int b;
public int c;
public Tri(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Tri tri = (Tri) o;
if (a != tri.a) return false;
if (b != tri.b) return false;
return c == tri.c;
}
@Override
public int hashCode() {
int result = a;
result = 31 * result + b;
result = 31 * result + c;
return result;
}
}
class Triple<T, U, P> {
public T a;
public U b;
public P c;
public Triple(T a, U b, P c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Triple<?, ?, ?> triple = (Triple<?, ?, ?>) o;
if (a != null ? !a.equals(triple.a) : triple.a != null) return false;
return b != null ? b.equals(triple.b) : triple.b == null;
}
@Override
public int hashCode() {
int result = a != null ? a.hashCode() : 0;
result = 31 * result + (b != null ? b.hashCode() : 0);
return result;
}
}
class Scanner {
BufferedReader in;
StringTokenizer tok;
public Scanner(InputStream in) {
this.in = new BufferedReader(new InputStreamReader(in));
tok = new StringTokenizer("");
}
private String tryReadNextLine() {
try {
return in.readLine();
} catch (Exception e) {
throw new InputMismatchException();
}
}
public String nextToken() {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(next());
}
return tok.nextToken();
}
public String next() {
String newLine = tryReadNextLine();
if (newLine == null)
throw new InputMismatchException();
return newLine;
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(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>
using namespace std;
const int MX = 2e6 + 5, N = 1e5 + 5;
int n, m, k;
vector<pair<int, int> > daysIn[MX], daysOut[MX];
long long costIn[MX], costOut[MX];
multiset<int> sIn[N], sOut[N];
long long ans = 1e9 * 1ll * 1e9;
int main() {
scanf("%d %d %d", &n, &m, &k);
int d, f, t, c;
for (int i = 1; i <= m; i++) {
scanf("%d %d %d %d", &d, &f, &t, &c);
if (f != 0) {
daysIn[d].push_back(make_pair(f, c));
} else {
daysOut[d].push_back(make_pair(t, c));
sOut[t].insert(c);
}
}
costIn[0] = 1e9 * 1ll * 1e9;
for (int i = 1; i <= n; i++) {
if ((int(sOut[i].size())) == 0) {
costOut[1] = 1e9 * 1ll * 1e9;
break;
}
costOut[1] += *(sOut[i].begin());
}
long long cstIn = 0, cntt = 0;
for (int i = 1; i <= 1e6; i++) {
costIn[i] = 1e9 * 1ll * 1e9;
for (int j = 0; j < (int(daysIn[i].size())); j++) {
int x = daysIn[i][j].first;
int cost = daysIn[i][j].second;
if ((int(sIn[x].size())) == 0) {
cstIn += cost;
cntt++;
sIn[x].insert(cost);
} else {
cstIn -= *(sIn[x].begin());
sIn[x].insert(cost);
cstIn += *(sIn[x].begin());
}
}
costOut[i + 1] = costOut[i];
for (int j = 0; j < (int(daysOut[i].size())); j++) {
int x = daysOut[i][j].first;
int cost = daysOut[i][j].second;
if (((int(sOut[x].size())) != 1) && (costOut[i + 1] != 1e9 * 1ll * 1e9)) {
costOut[i + 1] -= *(sOut[x].begin());
} else {
costOut[i + 1] = 1e9 * 1ll * 1e9;
}
sOut[x].erase(sOut[x].lower_bound(cost));
if ((int(sOut[x].size())) != 0) {
costOut[i + 1] += *(sOut[x].begin());
}
}
if (cntt == n) {
costIn[i] = cstIn;
}
}
for (int i = 1; i <= 1e6 - k - 1; i++) {
if (costIn[i] + costOut[i + k + 1] < ans) {
ans = costIn[i] + costOut[i + k + 1];
}
}
if (ans == 1e9 * 1ll * 1e9) {
ans = -1;
}
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.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));
TreeMap<Integer, Long> arriveTotalCosts = buildTotalCosts(arriveFlights, n);
TreeMap<Integer, Long> departTotalCosts = buildTotalCosts(departFlights, n);
if(arriveTotalCosts.isEmpty() || departTotalCosts.isEmpty()) {
System.out.println(-1);
return;
}
long minTotalCost = -1L;
Iterator<Map.Entry<Integer, Long>> arriveCostIt = arriveTotalCosts.entrySet().iterator();
Iterator<Map.Entry<Integer, Long>> departCostIt = departTotalCosts.entrySet().iterator();
int currentDepartDay = -1;
long currentDepartCost = -1L;
while(arriveCostIt.hasNext()) {
Map.Entry<Integer, Long> entry1 = arriveCostIt.next();
int arriveDay = entry1.getKey();
long arriveCost = entry1.getValue();
if(currentDepartDay - arriveDay > k) {
minTotalCost = Math.min(minTotalCost, arriveCost + currentDepartCost);
}
else {
while (departCostIt.hasNext()) {
Map.Entry<Integer, Long> entry2 = departCostIt.next();
int departDay = entry2.getKey();
long departCost = entry2.getValue();
if (departDay - arriveDay > k) {
if (minTotalCost == -1L || arriveCost + departCost < minTotalCost) {
minTotalCost = arriveCost + departCost;
}
currentDepartDay = departDay;
currentDepartCost = departCost;
break;
}
}
}
}
System.out.println(minTotalCost);
}
private static TreeMap<Integer, Long> buildTotalCosts(List<Flight> flights, int n) {
long totalCost = 0L;
TreeMap<Integer, Long> costMap = new TreeMap<>();
Map<Integer, Integer> city2cost = new HashMap<>();
for(Flight flight : flights) {
Integer oldCost = city2cost.get(flight.city);
if(oldCost != null && oldCost < flight.cost)
continue;
city2cost.put(flight.city, flight.cost);
totalCost += flight.cost - (oldCost == null ? 0 : oldCost);
if(city2cost.size() == n) {
costMap.put(flight.day, totalCost);
}
}
return costMap;
}
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;
}
}
} | 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;
bool visited[1000000 + 10];
long long int costin[1000000 + 10], dpin[1000000 + 10];
long long int costout[1000000 + 10], dpout[1000000 + 10];
void fun() {
for (int i = 0; i < 1000000 + 5; i++) {
dpin[i] = -1;
dpout[i] = -1;
}
}
int main() {
fun();
int n, m, k, a, b, c, d;
vector<pair<int, pair<int, int> > > vin, vout;
cin >> n >> m >> k;
for (int i = 0; i < m; i++) {
scanf("%d %d %d %d", &a, &b, &c, &d);
if (c == 0) {
vin.push_back(make_pair(a, make_pair(b, d)));
} else {
vout.push_back(make_pair(a, make_pair(c, d)));
}
}
sort(vin.begin(), vin.end());
sort(vout.begin(), vout.end(), greater<pair<int, pair<int, int> > >());
long long int val = 0, indate = -1, outdate = -1, ct = 0;
for (int i = 0; i < vin.size(); i++) {
int date = vin[i].first, city = vin[i].second.first,
cst = vin[i].second.second;
if (!visited[city]) {
costin[city] = cst;
val += costin[city];
ct++;
visited[city] = 1;
} else if (visited[city]) {
if (costin[city] > cst) {
val -= costin[city] - cst;
costin[city] = cst;
}
}
dpin[date] = val;
if (ct == n && indate == -1) indate = date;
}
for (int i = 1; i <= 1000000; i++) {
if (dpin[i] == -1) dpin[i] = dpin[i - 1];
}
for (int i = 0; i <= 1000000 + 4; i++) {
visited[i] = 0;
}
val = 0, ct = 0;
for (int i = 0; i < vout.size(); i++) {
int date = vout[i].first, city = vout[i].second.first,
cst = vout[i].second.second;
if (!visited[city]) {
costout[city] = cst;
val += costout[city];
ct++;
visited[city] = 1;
} else if (visited[city]) {
if (costout[city] > cst) {
val -= costout[city] - cst;
costout[city] = cst;
}
}
dpout[date] = val;
if (ct == n && outdate == -1) {
outdate = date;
}
}
for (int i = 1e6; i >= 0; i--) {
if (dpout[i] == -1) dpout[i] = dpout[i + 1];
}
long long int ans = -1;
if (indate != -1 && outdate != -1 && indate + k < outdate) {
for (int i = indate; i <= outdate - k - 1; i++) {
if (ans == -1) {
ans = dpin[i] + dpout[i + k + 1];
} else {
ans = min(ans, dpin[i] + dpout[i + k + 1]);
}
}
cout << ans;
} 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 | import java.util.*;
public class JuryMeeting {
private ArrayList <Node> arriving, departing;
private int n, m, k;
private long [] costOfArriving, costOfDeparting;
public void minCostsArriving() {
Map<Integer,Integer> mp=new HashMap<Integer,Integer>();
long cost=0;
for(int i=0; i<arriving.size(); i++) {
if(mp.get(arriving.get(i).from)==null) {
cost+=arriving.get(i).cost;
mp.put(arriving.get(i).from, arriving.get(i).cost);
}else if(mp.get(arriving.get(i).from)>arriving.get(i).cost) {
cost-=mp.get(arriving.get(i).from);
cost+=arriving.get(i).cost;
mp.put(arriving.get(i).from, arriving.get(i).cost);
}
if(mp.size()==n) {
costOfArriving[i]=cost;
}
}
}
public void minCostsDeparting() {
Map<Integer,Integer> mp=new HashMap<Integer,Integer>();
long cost=0;
for(int i=departing.size()-1; i>=0; i--) {
if(mp.get(departing.get(i).to)==null) {
cost+=departing.get(i).cost;
mp.put(departing.get(i).to, departing.get(i).cost);
}else if(mp.get(departing.get(i).to)>departing.get(i).cost) {
cost-=mp.get(departing.get(i).to);
cost+=departing.get(i).cost;
mp.put(departing.get(i).to, departing.get(i).cost);
}
if(mp.size()==n) {
costOfDeparting[i]=cost;
}
}
}
public long solve() {
TreeMap<Integer,Integer> tree=new TreeMap<Integer,Integer>();
long answer=Long.MAX_VALUE;
minCostsArriving();
minCostsDeparting();
for(int i=0, j=0; i<departing.size(); i++){
if(costOfDeparting[i]==Long.MAX_VALUE){
continue;
}
while(j<arriving.size()-1 && arriving.get(j).day<departing.get(i).day-k){
if(costOfArriving[j]!=Long.MAX_VALUE){
answer=Math.min(answer, costOfArriving[j]+costOfDeparting[i]);
}
j++;
}
if(arriving.get(j).day<departing.get(i).day-k && costOfArriving[j]!=Long.MAX_VALUE){
answer=Math.min(answer, costOfArriving[j]+costOfDeparting[i]);
}
}
/*for(int i=0; i<arriving.size(); i++) {
tree.put(arriving.get(i).day, i);
}
for(int i=departing.size()-1; i>=0; i--) {
if(costOfDeparting[i]!=Long.MAX_VALUE) {
Map.Entry<Integer, Integer> e=tree.lowerEntry(departing.get(i).day-k);
if(e!=null && costOfArriving[e.getValue()]!=Long.MAX_VALUE) {
answer=Math.min(answer, costOfArriving[e.getValue()]+costOfDeparting[i]);
}
}
}*/
if(answer==Long.MAX_VALUE) {
return -1;
}else {
return answer;
}
}
public JuryMeeting() {
Scanner sc=new Scanner(System.in);
arriving=new ArrayList<Node>();
departing=new ArrayList<Node>();
n=sc.nextInt();
m=sc.nextInt();
k=sc.nextInt();
for(int i=0; i<m; i++) {
int d, f, t, c;
d=sc.nextInt();
f=sc.nextInt();
t=sc.nextInt();
c=sc.nextInt();
if(t==0) {
arriving.add(new Node(d,f,t,c));
}else {
departing.add(new Node(d,f,t,c));
}
}
costOfArriving = new long [m];
costOfDeparting = new long[m];
for(int i=0; i<m; i++) {
costOfArriving[i]=Long.MAX_VALUE;
costOfDeparting[i]=Long.MAX_VALUE;
}
Collections.sort(arriving);
Collections.sort(departing);
sc.close();
}
public static void main(String[] args) {
System.out.println(new JuryMeeting().solve());
}
}
class Node implements Comparable <Node>{
public int day, from, to, cost;
public Node(int d, int f, int t, int c) {
day=d;
from=f;
to=t;
cost=c;
}
public int compareTo(Node o) {
if(day<o.day) {
return -1;
}else {
return 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;
inline int read() {
int x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = x * 10 + ch - '0';
ch = getchar();
}
return x * f;
}
const int maxn = 1e5 + 50;
const long long inf = 0x3f3f3f3f3f3f3f3f;
struct Ticket {
int d, f, t, c;
friend bool operator<(const Ticket& x, const Ticket& y) { return x.d < y.d; }
} F[maxn];
int n, m, K, used[maxn], Micost[maxn];
long long pf[maxn], sf[maxn];
int main(int argc, char* argv[]) {
n = read(), m = read(), K = read();
for (int i = 1; i <= m; ++i)
F[i].d = read(), F[i].f = read(), F[i].t = read(), F[i].c = read();
sort(F + 1, F + m + 1);
memset(used, 0, sizeof(used));
memset(Micost, 0x3f, sizeof(Micost));
memset(pf, 0x3f, sizeof(pf));
memset(sf, 0x3f, sizeof(sf));
long long z = 0;
for (int i = 1, come = 0; i <= m; ++i) {
pf[i] = pf[i - 1];
if (F[i].f != 0) {
int s = F[i].f;
if (used[s] == 0) {
used[s] = 1;
Micost[s] = F[i].c;
++come;
} else
z -= Micost[s], Micost[s] = min(Micost[s], F[i].c);
z += Micost[s];
}
if (come == n) pf[i] = min(pf[i], z);
}
memset(used, 0, sizeof(used));
memset(Micost, 0x3f, sizeof(Micost));
z = 0;
for (int i = m, come = 0; i >= 1; --i) {
sf[i] = sf[i + 1];
if (F[i].t != 0) {
int s = F[i].t;
if (used[s] == 0) {
used[s] = 1;
Micost[s] = F[i].c;
++come;
} else
z -= Micost[s], Micost[s] = min(Micost[s], F[i].c);
z += Micost[s];
}
if (come == n) sf[i] = min(sf[i], z);
}
long long ans = inf;
for (int i = 1; i < m; ++i)
if (pf[i] != inf) {
int l = i + 1, r = m;
while (l < r) {
int mid = l + r >> 1;
if (F[mid].d - F[i].d > K)
r = mid;
else
l = mid + 1;
}
if (F[l].d - F[i].d > K && sf[l] != inf) ans = min(ans, pf[i] + sf[l]);
}
if (ans == inf) ans = -1;
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;
struct hi {
int d, f, t, c;
};
const int N = 1e6;
const long long INF = 1e17;
int n, m, k;
hi a[N + 5];
void enter() {
cin >> n >> m >> k;
for (int i = (1), _b = (m); i <= _b; ++i)
cin >> a[i].d >> a[i].f >> a[i].t >> a[i].c;
}
bool cmp(hi p, hi q) { return p.d < q.d; }
int cur[N + 5];
long long pre[N + 5], suf[N + 5];
void process() {
for (int i = (0), _b = (N); i <= _b; ++i) cur[i] = -1;
sort(a + 1, a + m + 1, cmp);
long long sum = 0;
int cnt = 0;
for (int i = (0), _b = (N); i <= _b; ++i) pre[i] = suf[i] = INF;
for (int i = (1), _b = (m); i <= _b; ++i)
if (a[i].t == 0) {
if (cur[a[i].f] == -1) {
cur[a[i].f] = a[i].c;
++cnt;
sum += a[i].c;
} else if (cur[a[i].f] > a[i].c) {
sum += -cur[a[i].f] + a[i].c;
cur[a[i].f] = a[i].c;
}
if (cnt == n) pre[a[i].d] = sum;
}
for (int i = (0), _b = (N); i <= _b; ++i) cur[i] = -1;
sum = 0;
cnt = 0;
for (int i = (m), _b = (1); i >= _b; --i)
if (a[i].f == 0) {
if (cur[a[i].t] == -1) {
cur[a[i].t] = a[i].c;
++cnt;
sum += a[i].c;
} else if (cur[a[i].t] > a[i].c) {
sum += -cur[a[i].t] + a[i].c;
cur[a[i].t] = a[i].c;
}
if (cnt == n) suf[a[i].d] = sum;
}
for (int i = (1), _b = (N); i <= _b; ++i) pre[i] = min(pre[i - 1], pre[i]);
for (int i = (N - 1), _b = (0); i >= _b; --i)
suf[i] = min(suf[i + 1], suf[i]);
long long ans = INF;
for (int lb = (1), _b = (N - k); lb <= _b; ++lb) {
ans = min(ans, pre[lb - 1] + suf[lb + k]);
}
if (ans >= INF) ans = -1;
cout << ans;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
enter();
process();
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 GCC optimize(2)
using namespace std;
inline void read(long long &x) {
x = 0;
long long f = 1;
char s = getchar();
while (s < '0' || s > '9') {
if (s == '-') f = -1;
s = getchar();
}
while (s >= '0' && s <= '9') {
x = (x << 3) + (x << 1) + (s ^ 48);
s = getchar();
}
x *= f;
}
inline long long Max(long long x, long long y) { return x > y ? x : y; }
inline long long Min(long long x, long long y) { return x < y ? x : y; }
inline long long Abs(long long x) {
if (x > 0) return x;
return -x;
}
vector<pair<long long, long long> > In[1000005], Out[1000005];
long long F1[1000005], Num1[1000005];
long long F2[1000005], Num2[1000005];
long long Ming[1000005], Minb[1000005];
int main() {
long long n, m, k;
read(n);
read(m);
read(k);
for (register int i = 1; i <= m; ++i) {
long long d, u, v, c;
read(d);
read(u);
read(v);
read(c);
if (!v)
In[d].push_back(pair<long long, long long>(u, c));
else
Out[d].push_back(pair<long long, long long>(v, c));
}
for (register int i = 1; i <= 1000005 - 5; ++i) {
F1[i] = F1[i - 1];
Num1[i] = Num1[i - 1];
int l = In[i].size();
for (register int j = 0; j < l; ++j) {
long long to = In[i][j].first, w = In[i][j].second;
if (!Ming[to]) {
Ming[to] = w;
Num1[i]++;
F1[i] += w;
} else if (Ming[to] > w) {
F1[i] -= (Ming[to] - w);
Ming[to] = w;
}
}
}
for (register int i = 1000005 - 5; i >= 1; --i) {
F2[i] = F2[i + 1];
Num2[i] = Num2[i + 1];
int l = Out[i].size();
for (register int j = 0; j < l; ++j) {
long long to = Out[i][j].first, w = Out[i][j].second;
if (!Minb[to]) {
Minb[to] = w;
Num2[i]++;
F2[i] += w;
} else if (Minb[to] > w) {
F2[i] -= (Minb[to] - w);
Minb[to] = w;
}
}
}
long long Ans = -1;
for (register int i = 1; i + k + 1 <= 1000005 - 5; ++i) {
if (Num1[i] == n && Num2[i + k + 1] == n) {
long long Wa = F1[i] + F2[i + k + 1];
if (Ans == -1)
Ans = Wa;
else
Ans = Min(Ans, Wa);
}
}
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;
long long a[1000005], b[1000005], c[1000005];
int arr[100005], back[100005];
int min_cost1[100005], min_cost2[100005];
int a_num = 0, b_num = 0;
struct node {
int time, from, to, val;
bool operator<(const node& n) const { return time < n.time; }
} f[100005];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, m, k;
cin >> n >> m >> k;
for (int i = 1; i <= m; i++) {
cin >> f[i].time >> f[i].from >> f[i].to >> f[i].val;
}
sort(f + 1, f + 1 + m);
int pre1 = 0, pre2 = m;
long long sum1 = 0, sum2 = 0;
for (int i = 1; i <= m; i++) {
if (a_num == n) {
for (int j = pre1 + 1; j <= f[i].time; j++) {
a[j] = a[j - 1];
}
pre1 = f[i].time;
}
if (f[i].to == 0) {
int z = f[i].from;
if (arr[z]) {
if (min_cost1[z] > f[i].val) {
sum1 -= min_cost1[z];
min_cost1[z] = f[i].val;
sum1 += min_cost1[z];
}
} else {
arr[z] = 1;
a_num++;
min_cost1[z] = f[i].val;
sum1 += f[i].val;
}
if (a_num == n) {
a[f[i].time] = sum1;
pre1 = f[i].time;
}
}
}
for (int i = m; i >= 1; i--) {
if (b_num == n) {
for (int j = pre2 - 1; j >= f[i].time; j--) {
b[j] = b[j + 1];
}
pre2 = f[i].time;
}
if (f[i].from == 0) {
int z = f[i].to;
if (back[z]) {
if (min_cost2[z] > f[i].val) {
sum2 -= min_cost2[z];
min_cost2[z] = f[i].val;
sum2 += min_cost2[z];
}
} else {
back[z] = 1;
b_num++;
min_cost2[z] = f[i].val;
sum2 += f[i].val;
}
if (b_num == n) {
b[f[i].time] = sum2;
pre2 = f[i].time;
}
}
}
long long ans = 1e18;
for (int i = 1; i <= 1e6; i++) {
if (a[i] == 0) continue;
int t = i + k + 1;
if (t > 1e6 || b[t] == 0) continue;
ans = min(ans, a[i] + b[t]);
}
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 unsigned long long oo = 1ll << 40;
const unsigned long long MX = 2000000;
struct data {
int t, l, c;
bool operator<(const data &in) const { return t < in.t; }
};
vector<data> v, b;
unsigned long long now[MX];
unsigned long long prefix[MX];
unsigned long long suffix[MX];
int main() {
unsigned long long n, m, k;
cin >> n >> m >> k;
while (m--) {
int t, s, d, c;
cin >> t >> s >> d >> c;
if (d == 0) v.push_back({t, s, c});
if (s == 0) b.push_back({-t, d, c});
}
sort(v.begin(), v.end());
sort(b.begin(), b.end());
unsigned long long p = 0, f = 0;
for (int i = 1; i < n + 1; i++) p += (now[i] = oo);
for (int i = 0; i < MX; i++) {
while (f < v.size() && v[f].t == i) {
if (v[f].c < now[v[f].l]) {
p -= now[v[f].l] - v[f].c;
now[v[f].l] = v[f].c;
}
f++;
}
prefix[i] = p;
}
p = 0, f = 0;
for (int i = 1; i < n + 1; i++) p += (now[i] = oo);
for (int i = 0; i < b.size(); i++) b[i].t = -b[i].t;
for (int i = MX - 1; i >= 0; i--) {
while (f < b.size() && b[f].t == i) {
if (b[f].c < now[b[f].l]) {
p -= now[b[f].l] - b[f].c;
now[b[f].l] = b[f].c;
}
f++;
}
suffix[i] = p;
}
unsigned long long ans = oo;
for (int i = 0; i < MX - k - 2; i++) {
ans = min(ans, prefix[i] + suffix[i + k + 1]);
}
if (ans >= oo)
cout << -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;
const int N = 1e5 + 5;
const int M = 1e6 + 5;
const int INF = 0x3f3f3f3f;
const long long llINF = 0x3f3f3f3f3f3f3f3f;
const int mod = 998244353;
long long read() {
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();
}
return x * w;
}
struct node {
int d, f, t, c;
} a[N];
bool cmp(node x, node y) { return x.d < y.d; }
long long sum1[M], sum2[M];
long long val[N];
int main() {
int n, m, k, d, f, t, c, en = 0;
n = read(), m = read(), k = read();
for (int i = 1; i <= m; ++i) {
d = read(), f = read(), t = read(), c = read();
a[i] = {d, f, t, c};
en = max(en, d);
}
sort(a + 1, a + m + 1, cmp);
memset((sum1), (llINF), sizeof(sum1));
memset((sum2), (llINF), sizeof(sum2));
memset((val), (llINF), sizeof(val));
long long sum = 0;
int len = 0;
for (int i = 1; i <= m; ++i) {
if (a[i].f == 0) continue;
if (val[a[i].f] == llINF) {
val[a[i].f] = a[i].c;
sum += a[i].c;
len++;
} else if (val[a[i].f] > a[i].c) {
sum += -val[a[i].f] + a[i].c;
val[a[i].f] = a[i].c;
}
if (len == n) {
sum1[a[i].d] = sum;
}
}
for (int i = 1; i <= en; ++i) {
if (sum1[i - 1] != llINF) {
sum1[i] = min(sum1[i - 1], sum1[i]);
}
}
len = 0;
memset((val), (llINF), sizeof(val));
sum = 0;
for (int i = m; i >= 1; --i) {
if (a[i].t == 0) continue;
if (val[a[i].t] == llINF) {
val[a[i].t] = a[i].c;
sum += a[i].c;
len++;
} else if (val[a[i].t] > a[i].c) {
sum += -val[a[i].t] + a[i].c;
val[a[i].t] = a[i].c;
}
if (len == n) {
sum2[a[i].d] = sum;
}
}
for (int i = en - 1; i >= 1; --i) {
if (sum2[i + 1] != llINF) {
sum2[i] = min(sum2[i + 1], sum2[i]);
}
}
long long ans = llINF;
for (int i = 1; i <= en - k - 1; ++i) {
ans = min(ans, sum1[i] + sum2[i + k + 1]);
}
if (ans == llINF)
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 n, m, k, s, l, r, md, cnt, mn = -1, ans, sz[100005], k1[100005],
k2[100005], mi[100005], x[100005],
y[100005];
bool v[100005];
vector<long long> b[100005], c[100005], u[100005];
struct st {
long long ti, st, en, num;
} a[100005];
bool comp(st p, st q) { return p.ti < q.ti; }
int main() {
long long i, j, t, z, t2;
cin >> n >> m >> k;
for (i = 0; i < m; i++) {
scanf("%I64d %I64d %I64d %I64d", &a[i].ti, &a[i].st, &a[i].en, &a[i].num);
}
sort(a, a + m, comp);
for (i = 0; i < m; i++) y[i] = a[i].ti;
cnt = 0;
s = 0;
x[m] = -1;
for (i = m - 1; i >= 0; i--) {
t = a[i].en;
if (a[i].st != 0) {
x[i] = x[i + 1];
continue;
}
if (mi[t] == 0) cnt++;
s -= mi[t];
if (mi[t] == 0 || mi[t] > a[i].num) {
mi[t] = a[i].num;
}
s += mi[t];
if (cnt < n)
x[i] = -1;
else
x[i] = s;
}
cnt = 0;
s = 0;
for (i = 0; i < m; i++) {
t = a[i].st;
if (t == 0) continue;
if (!v[t]) {
v[t] = true;
k1[t] = a[i].num;
cnt++;
} else {
s -= k1[t];
k1[t] = min(k1[t], a[i].num);
}
s += k1[t];
t2 = lower_bound(y, y + m, a[i].ti + k + 1) - y;
if (x[t2] != -1 && cnt == n) {
if (mn == -1 || s + x[t2] < mn) mn = s + x[t2];
}
}
cout << mn;
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 = 1000000000000ll;
int main() {
int n, m, K;
scanf("%d%d%d", &n, &m, &K);
K++;
vector<vector<pair<int, int> > > af(n), df(n);
vector<pair<int, int> > ev(m);
for (int t = 0; t < m; t++) {
int d, a, b, c;
scanf("%d%d%d%d", &d, &a, &b, &c);
if (b == 0) {
a--;
af[a].push_back(make_pair(d, c));
ev[t] = make_pair(d, -a - 1);
} else if (a == 0) {
b--;
df[b].push_back(make_pair(d, c));
ev[t] = make_pair(d - K, b + 1);
}
}
sort(ev.begin(), ev.end());
vector<vector<long long> > mc1(n), mc2(n);
for (int i = 0; i < n; i++) {
sort(af[i].begin(), af[i].end());
mc1[i] = vector<long long>(af[i].size() + 1);
mc1[i][0] = INF;
for (int t = 0; t < af[i].size(); t++) {
mc1[i][t + 1] = min(mc1[i][t], (long long)af[i][t].second);
}
sort(df[i].begin(), df[i].end());
mc2[i] = vector<long long>(df[i].size() + 1);
mc2[i][df[i].size()] = INF;
for (int t = df[i].size() - 1; t >= 0; t--) {
mc2[i][t] = min(mc2[i][t + 1], (long long)df[i][t].second);
}
}
vector<int> f1(n, 0), f2(n, 0);
long long S = 0ll;
for (int i = 0; i < n; i++) S += mc1[i][0] + mc2[i][0];
long long ans = S;
for (int t = 0; t < m; t++) {
int q = ev[t].second;
if (q < 0) {
int i = -q - 1;
S += mc1[i][f1[i] + 1] - mc1[i][f1[i]];
f1[i]++;
} else {
int i = q - 1;
S += mc2[i][f2[i] + 1] - mc2[i][f2[i]];
f2[i]++;
}
ans = min(ans, S);
}
printf("%lld\n", ans < INF ? ans : -1);
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 MAXX = 1e6 + 5;
long long n, m, k;
struct ask {
long long x;
long long st;
};
vector<ask> v1[MAXX], v2[MAXX];
long long in[MAXX], out[MAXX];
long long taken1[MAXX], taken2[MAXX];
const long long INF = 1e17;
void read() {
long long i, j;
ask aa;
long long a1, a2, a3, a4;
cin >> n >> m >> k;
for (i = 0; i < m; i++) {
cin >> a1 >> a2 >> a3 >> a4;
if (a3 == 0) {
aa.x = a2;
aa.st = a4;
v1[a1].push_back(aa);
} else {
aa.x = a3;
aa.st = a4;
v2[a1].push_back(aa);
}
}
}
void solve() {
long long i, j, sum = 0;
long long cnt = 0, sz;
ask aa;
for (i = 0; i < MAXX; i++) {
in[i] = out[i] = INF;
}
for (i = 1; i < MAXX; i++) {
sz = v1[i].size();
if (!sz) {
in[i] = in[i - 1];
continue;
}
for (j = 0; j < sz; j++) {
aa = v1[i][j];
if (!taken1[aa.x]) {
cnt++;
sum += aa.st;
taken1[aa.x] = aa.st;
} else {
sum -= taken1[aa.x];
taken1[aa.x] = min(taken1[aa.x], aa.st);
sum += taken1[aa.x];
}
if (cnt == n) {
in[i] = sum;
} else
in[i] = INF;
}
}
cnt = 0;
sum = 0;
for (i = MAXX - 2; i >= 1; i--) {
sz = v2[i].size();
if (!sz) {
out[i] = out[i + 1];
continue;
}
for (j = 0; j < sz; j++) {
aa = v2[i][j];
if (!taken2[aa.x]) {
cnt++;
sum += aa.st;
taken2[aa.x] = aa.st;
} else {
sum -= taken2[aa.x];
taken2[aa.x] = min(taken2[aa.x], aa.st);
sum += taken2[aa.x];
}
if (cnt == n) {
out[i] = sum;
} else
out[i] = INF;
}
}
}
int main() {
read();
solve();
long long i;
long long ans = INF;
long long nz;
for (i = 1; i < MAXX - k; i++) {
if (in[i - 1] == INF || out[i + k] == INF) {
continue;
}
nz = in[i - 1] + out[i + k];
ans = min(ans, nz);
}
if (ans == INF) ans = -1;
cout << ans << endl;
return 0;
}
| CPP |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int main() {
long long int n, k;
cin >> n >> k;
long long int p[n], mx = 0;
std::vector<long long int> v;
for (int i = 0; i < n; i++) {
cin >> p[i];
v.push_back(p[i]);
if (p[i] > mx) mx = p[i];
}
for (int i = 0; i < n; i++) {
int cmp = 1;
if (p[i] == mx) {
cout << p[i] << endl;
break;
}
for (int j = 1; j <= k; j++) {
if (v[i] < v[i + j]) {
cmp = 0;
v.push_back(v[i]);
break;
}
v.push_back(v[i + j]);
if (j == k - 1 && i > 0) break;
}
if (cmp == 1) {
cout << p[i] << endl;
break;
}
}
}
| CPP |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | n,k=[int(i) for i in input().split()]
a=[int(i) for i in input().split()]
d=a[0]
t=0
h=0
for i in range(1,n):
if d>a[i]:
t+=1
if t>=k:
print(d)
h=1
break
else:
t=1
d=a[i]
if h==0:
print(max(a))
| PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | import queue
from collections import deque
def readTuple():
return input().split()
def readInts():
return tuple(map(int, readTuple()))
def solve():
n,k = readInts()
if k >= 2000:
print(n)
return
wins = 0
powers = deque(readInts())
while True:
a = powers.popleft()
b = powers.popleft()
if wins >= k:
print(a)
break
if a>b:
wins += 1
else:
wins = 1
a,b = b,a
powers.appendleft(a)
powers.append(b)
if __name__ == '__main__':
solve()
| PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 |
import java.util.Scanner;
public class B879 {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int a =sc.nextInt();
long b=sc.nextLong();
int[] array=new int[a];
for (int i=0;i<array.length;i++)
{
array[i]=sc.nextInt();
}
if (b<=array.length-1)
{
long bb=array[0];
long cc=b;
long hh=0;
int count=0;
for (int i=1;i<array.length;i++)
{
if (hh>=cc)
{
System.out.println(bb);
count++;
break;
}
if (bb>array[i])
{
hh++;
}else {
hh=1;
bb=array[i];
}
}
if (count==0)
{
System.out.println(bb);
}
}else {
int bb=0;
for (int i=0;i<array.length;i++)
{
if (array[i]>bb)
{
bb=array[i];
}
}
System.out.println(bb);
}
}
}
| JAVA |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int mxn = 505;
int n, cnt;
long long k, maxi, tmp, a[mxn];
;
int main() {
cin >> n >> k;
cin >> a[1];
maxi = a[1];
for (int i = 2; i <= n; i++) {
cin >> a[i];
if (maxi > a[i])
cnt++;
else {
if (cnt >= k) {
cout << maxi << endl;
return 0;
}
maxi = a[i];
cnt = 1;
}
}
cout << maxi << endl;
}
| CPP |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | #developer at Imperial Arkon
n,k = [int(x) for x in input().split()]
power = [int(x) for x in input().split()]
i=0
if k>=n: print(max(power))
else:
while i<n:
flag,flag2 = 0,0
if i==0: withPlayers = i+k+1
else: withPlayers = i+k
for j in range(i+1, withPlayers):
if j==n:
print(power[tempWinner])
flag2=1 #and break
break
if power[j]>power[i]:
i,flag=j,1
tempWinner=i
break
if j==withPlayers-1 and flag==0:
if not flag2: print(power[i])
flag2=1
break
if flag==0: i+=1
if flag2: break
if flag2==0: print(power[tempWinner]) | PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | n,k=map(int,input().split())
q=list(map(int,input().split()))
mx=max(q)
if k>=n-1:
print(mx)
else:
i=0
x=0
f=False
for r in range(1,n-1):
if q[r]>q[i]:
i=r
x=1
else:
x+=1
if x==k:
f=True
print(q[i])
break
if not f:
print(mx) | PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | n, k = map(int, input().split())
a = list(map(int, input().split()))
c = a + a
if k >= n - 1:
print(n)
else:
for i in range(n):
if a[i] > max(c[i + 1:i + 1 + k - 1 * (i != 0)]):
print(a[i])
break | PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
inline int read() {
char c;
int s = 0, t = 1;
while (!isdigit(c = getchar()))
if (c == '-') t = -1;
do {
s = s * 10 + c - '0';
} while (isdigit(c = getchar()));
return s * t;
}
inline long long readl() {
char c;
long long s = 0;
int t = 1;
while (!isdigit(c = getchar()))
if (c == '-') t = -1;
do {
s = s * 10 + c - '0';
} while (isdigit(c = getchar()));
return s * t;
}
int a[101000];
int main() {
long long n, k;
n = readl(), k = readl();
int ans = 0;
for (int i = 1; i <= n; i++) {
a[i] = read();
ans = max(ans, a[i]);
}
if (k >= n - 1) {
printf("%d\n", ans);
return 0;
}
int l = 1, r = n + 1;
ans = 0;
while (1) {
if (a[l] > a[l + 1]) {
a[r++] = a[l + 1];
a[l + 1] = a[l++];
ans++;
if (ans >= k) {
printf("%d\n", a[l]);
return 0;
}
} else {
a[r++] = a[l++];
ans = 1;
}
}
}
| CPP |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | n, k = map(int, input().split())
a = list(map(int, input().split()))
if k >= n - 1:
print(n)
else:
j = 0
cnt = 0
for i in range(1, n):
if a[i] < a[j]:
cnt += 1
if cnt == k:
print(a[j])
break
else:
j = i
cnt = 1
else:
print(n)
| PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | n, k = map(int, input().split())
a = list(map(int, input().split()))
dp = [0] * (n + 1)
maxm = max(a[0], a[1])
dp[maxm] = 1
for i in range(2, n):
maxm = max(maxm, a[i])
dp[maxm] += 1
if dp[maxm] >= k:
ans = maxm
break
else:
ans = max(a)
print(ans) | PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | n, k = tuple([int(x) for x in raw_input().rstrip().split()])
a = [int(x) for x in raw_input().rstrip().split()]
if k > len(a):
print max(a)
else:
streak = 0
while(True):
w, l = max(a[0], a[1]), min((a[0], a[1]))
if w == a[0]:
streak += 1
else:
streak = 1
a = [w] + a[2:] + [l]
if streak == k:
break
print a[0] | PYTHON |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int main() {
long long int n;
long long int k;
cin >> n >> k;
long long int a[n + 1];
for (int i = 0; i < n; i++) {
cin >> a[i];
}
long long int v[1000] = {0};
long long int ans = 0;
for (int i = 0; i < n; i++) {
if (a[i] > ans) {
ans = a[i];
}
}
long long int ans1 = a[0];
for (int i = 1; i < n; i++) {
if (ans1 > a[i]) {
v[ans1] = v[ans1] + 1;
} else {
ans1 = a[i];
v[a[i]] = v[a[i]] + 1;
}
}
int f = 0;
for (int i = 0; i < n; i++) {
if (v[a[i]] >= k) {
f = 1;
ans1 = a[i];
break;
}
}
if (f == 0) {
ans1 = ans;
}
cout << ans1;
return 0;
}
| CPP |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | n,k = map(int,input().split())
List = [int(x) for x in input().split()]
i = 1
t = 0
Max = List[0]
while(i<n):
X = max(Max,List[i])
if(X == Max):
t+=1
else:
Max = X
t=1
if(t==k):
break
i+=1
print(Max) | PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 |
import java.util.*;
/**
*
* @author Anjali
*/
public class Tennis {
/**
* @param args the command line arguments
*/
public static void function1(int ar[],long n,long k)
{
long st=0;
int ans = ar[0];
for(int i=1;i<n;i++)
{
if(st>=k)
{
System.out.println(ans);
return;
}
else if(ans>ar[i])
{
st++;
}
else
{
st=1;
ans=ar[i];
}
}
System.out.println(ans);
}
public static void main(String[] args) {
// TODO code application logic here
Scanner in = new Scanner(System.in);
long n = in.nextLong();
int ar[]= new int[(int)n];
long k = in.nextLong();
for(int i=0;i<n;i++)
{
ar[i] = in.nextInt();
}
Tennis.function1(ar, n,k);
}
}
| JAVA |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | from sys import stdin,stdout
n,k = map(int,stdin.readline().split())
p = list(map(int,stdin.readline().split()))
if k >= (n-1):
p.sort(reverse=True)
stdout.write(str(p[0]))
else:
n1 = p[0]
del p[0]
c = 0
for item in p:
if item > n1:
n1 = item
c = 1
else:
c = c+1
if c == k:
break
stdout.write(str(n1))
| PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
/**
* 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;
Scanner in = new Scanner(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, Scanner in, PrintWriter out) {
int n = in.nextInt();
long k = in.nextLong();
int array[] = new int[n];
int max = Integer.MIN_VALUE, maxindex = -1;
for (int i = 0; i < n; i++) {
array[i] = in.nextInt();
if (array[i] > max) {
max = array[i];
maxindex = i;
}
}
int count = 0;
for (int i = 0; i < maxindex && maxindex - i - 1 + count >= k; i++) {
int j = i + 1;
for (; j < maxindex; j++) {
if (count == k) {
out.println(array[i]);
return;
}
if (array[i] > array[j]) count++;
else {
i = j - 1;
count = 1;
break;
}
}
if (count == k) {
out.println(array[i]);
return;
}
}
out.println(n);
}
}
}
| JAVA |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | /**
* DA-IICT
* Author : PARTH PATEL
*/
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 B879
{
public static int mod = 1000000007;
static FasterScanner in = new FasterScanner();
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args)
{
int n=in.nextInt();
long k=in.nextLong();
int[] arr=new int[n+1];
int maxi=-1;
for(int i=1;i<=n;i++)
{
arr[i]=in.nextInt();
maxi=max(maxi, arr[i]);
}
if(k>=n)
{
out.println(maxi);
out.flush();
return;
}
else
{
ArrayList<Integer> queue=new ArrayList<>();
for(int i=1;i<=n;i++)
{
queue.add(arr[i]);
}
for(int i=1;i<=n;i++)
{
//System.out.println(queue);
/*boolean bool=true;
for(int j=1;j<=k;j++)
{
if(queue.get(j)<queue.get(0))
continue;
else
bool=false;
}
if(bool)
{
out.println(queue.get(0));
out.flush();
return;
}*/
int a1=queue.get(0);
int a2=queue.get(1);
queue.remove(new Integer(a1));
queue.remove(new Integer(a2));
if(a1>a2)
{
queue.add(0, a1);
queue.add(a2);
boolean bool=true;
for(int j=1;j<k;j++)
{
if(queue.get(j)<queue.get(0))
continue;
else
bool=false;
}
if(bool)
{
out.println(queue.get(0));
out.flush();
return;
}
}
else
{
queue.add(0,a2);
queue.add(a1);
boolean bool=true;
for(int j=1;j<k;j++)
{
if(queue.get(j)<queue.get(0))
continue;
else
bool=false;
}
if(bool)
{
out.println(queue.get(0));
out.flush();
return;
}
}
}
out.println(queue.get(0));
}
out.close();
}
public static long pow(long x, long n, long mod)
{
long res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p) % mod)
{
if ((n & 1) != 0)
{
res = (res * p % mod);
}
}
return res;
}
public static long gcd(long n1, long n2)
{
long r;
while (n2 != 0)
{
r = n1 % n2;
n1 = n2;
n2 = r;
}
return n1;
}
public static long lcm(long n1, long n2)
{
long answer = (n1 * n2) / (gcd(n1, n2));
return answer;
}
static class FasterScanner
{
private byte[] buf = new byte[1024];
private int curChar;
private int snumChars;
public int read()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = System.in.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 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 nextString()
{
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;
}
private 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 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma")
#pragma GCC optimize("unroll-loops")
using namespace std;
long long int MOD = 998244353;
double eps = 1e-12;
void solve();
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long int t = 1;
while (t--) {
solve();
}
return 0;
}
void solve() {
long long int n, k;
cin >> n >> k;
deque<long long int> v(n);
for (long long int i = 0; i < n; i++) {
cin >> v[i];
}
if (k >= n) {
cout << *max_element(v.begin(), v.end()) << endl;
} else {
long long int st[n];
memset(st, 0, sizeof(st));
while (true) {
long long int a = v[0];
long long int b = v[1];
v.pop_front(), v.pop_front();
if (a > b) {
st[a - 1]++;
v.push_front(a);
v.push_back(b);
} else {
st[b - 1]++;
v.push_front(b);
v.push_back(a);
}
long long int max = *max_element(st, st + n);
if (max >= k) {
for (long long int i = 0; i < n; i++) {
if (st[i] == max) {
cout << i + 1 << endl;
return;
}
}
}
}
}
}
| CPP |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 |
firstLine = input().split(' ')
n = int(firstLine[0])
k = int(firstLine[1])
secondLine = input()
powerArr = [int(x) for x in secondLine.split(' ')]
firstMatchPlayed=0
for x in range(n):
playerStrength = powerArr[x]
playerPos = x
xcount =0
j=x+1
if j>n-1:
j=0
if firstMatchPlayed==0:
niter=k
else:
niter=k-1
while(niter>0):
if (powerArr[j]>playerStrength):
break
else:
j+=1
if j>n-1:
j=0
niter-=1
xcount+=1
if (xcount>n-1):
break
firstMatchPlayed+=1
if (niter==0) or (xcount>n-1):
print(playerStrength)
break
| PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | #include <bits/stdc++.h>
int main() {
int n;
long long k, now = 0LL;
scanf("%d%I64d", &n, &k);
int *mas = new int[n * 4], a;
for (int i = 0; i < n; i++) {
scanf("%d", &mas[i]);
mas[i + n + n + n] = (mas[i + n + n] = (mas[i + n] = mas[i]));
}
a = mas[0];
for (int i = 1; i < n; i++) {
if (mas[i] > a) {
a = mas[i];
now = 1LL;
} else
now++;
if (now == k) break;
}
printf("%d\n", a);
return 0;
}
| CPP |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int main() {
long long int n, k, temp;
cin >> n >> k;
queue<long long int> q1;
for (long long int i = 0; i < n; i++) {
cin >> temp;
q1.push(temp);
}
if (k <= n - 1) {
long long int count = 0;
long long int val = q1.front();
q1.pop();
while (1) {
temp = q1.front();
if (temp < val) {
count++;
q1.pop();
q1.push(temp);
} else {
count = 1;
q1.pop();
q1.push(val);
val = temp;
}
if (count == k) {
break;
}
}
cout << val;
} else {
long long int max1 = 0;
while (!q1.empty()) {
temp = q1.front();
max1 = max(max1, temp);
q1.pop();
}
cout << max1;
}
return 0;
}
| CPP |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | n, k = map(int, input().split())
a = list(map(int, input().split()))
ans = max(a)
tmp = a[0]
cnt = 0
for i in range(1, n):
if tmp < a[i]:
tmp = a[i]
cnt = 1
else:
cnt += 1
if cnt == k:
ans = tmp
break
print(ans)
| PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | s=input().split()
n=int(s[0])
k=float(s[1])
s=input().split()
i=0
a=[]
while i<n :
a.append(int(s[i]))
i+=1
p=0
t=a.index(n)
if k<t :
while p<k :
if a[0]==n :
break
if a[0]>a[1] :
p+=1
if p==k :
break
a.append(a[1])
a.pop(1)
else :
p=1
a.append(a[0])
a.pop(0)
print(a[0])
else :
print(n)
| PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | import Queue
N, K = map(int, raw_input().split())
A = map(int, raw_input().split())
Q = Queue.Queue()
if (K > N):
print max(A)
else:
B, W = A[0], 0
for i in range(1, N):
Q.put(A[i])
while True:
top = Q.get()
if B > top:
Q.put(top)
W += 1
else:
Q.put(B)
B, W = top, 1
if W >= K:
print(B)
break | PYTHON |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | n, k = map(int, input().split())
p = list(map(int, input().split()))
best = 0
for x in p:
best = max(best, x)
wins = 0
b = -1
while wins < k:
if p[0] > p[1]:
l = p[1]
w = p[0]
p.pop(1)
else:
l = p[0]
w = p[1]
p.pop(0)
p.append(l)
if w == b:
wins += 1
else:
wins = 1
b = w
if b == best:
break
print(b)
| PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 507 * 507;
long long n, k;
int a[maxn];
int win[maxn];
int maxx = 0;
int main() {
cin >> n >> k;
for (int i = 0; i < n; i++) cin >> a[i], maxx = max(maxx, a[i]);
if (n <= k)
cout << maxx;
else {
int l = 0, r = 1;
int rr = n;
int f = 0;
for (;;) {
if (a[l] > a[r]) {
a[rr++] = a[r], win[a[l]]++;
if (win[a[l]] == k) f = a[l];
r = max(l, r) + 1;
} else {
a[rr++] = a[l], win[a[r]]++;
if (win[a[r]] == k) f = a[l];
l = max(l, r) + 1;
}
if (l > r) swap(l, r);
if (win[a[l]] == k) break;
}
cout << f << "\n";
}
}
| CPP |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n;
long long k;
cin >> n >> k;
vector<int> v(n);
for (int i = 0; i < n; i++) {
cin >> v[i];
}
if (k >= n) {
cout << n << endl;
return 0;
}
int cnt;
int i, j;
if (v[0] < v[1]) {
i = 1;
j = 2;
cnt = 1;
} else {
i = 0;
j = 1;
cnt = 0;
}
if (v[0] == n) {
cout << n << endl;
return 0;
}
while (j < n && cnt <= k) {
if (v[j] < v[i]) {
cnt++;
j++;
if (cnt == k) {
cout << v[i] << endl;
return 0;
}
} else {
i = j;
j = i + 1;
if (v[i] == n) {
cout << n << endl;
return 0;
}
cnt = 1;
}
}
cout << n << endl;
return 0;
}
| CPP |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
int n;
long long int k;
cin >> n >> k;
queue<int> q;
int maxx = INT_MIN;
for (int i = 0; i < n; i++) {
int ele;
cin >> ele;
maxx = max(maxx, ele);
q.push(ele);
}
if (k >= n - 1)
cout << maxx;
else {
int wins = 0, winner = q.front();
q.pop();
while (wins < k) {
int p2 = q.front();
q.pop();
if (winner < p2) {
winner = p2;
wins = 1;
q.push(winner);
} else {
wins++;
q.push(p2);
}
}
cout << winner;
}
return 0;
}
| CPP |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | #author: riyan
if __name__ == '__main__':
n, k = map(int, input().strip().split())
arr = list(map(int, input().strip().split()))
i, cnt, ans = 0, 0, 0
while i < n and cnt < k:
if ans:
if ans > arr[i]:
cnt += 1
else:
cnt = 1
else:
cnt = 0
ans = max([ans, arr[i]])
i += 1
print(ans) | PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Scholae {
public static void main(String[] args) throws IOException {
// BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Scanner in = new Scanner(System.in);
new Scholae().run(in);
}
private void run(Scanner in) throws IOException {
// String[] s = in.readLine();
long n = in.nextLong();
long m = in.nextLong();
ArrayList<Long> st = new ArrayList<>();
long wins = 0;
long max = 0;
for (int i = 0; i < n; i++) {
long l = in.nextLong();
if (l > max)
max = l;
st.add(l);
}
while (wins < m) {
if (st.get(0) > st.get(1)) {
if (st.get(0) == max)
wins = m+1;
else {
wins++;
long i = st.get(1);
st.remove(1);
st.add(i);
}
} else {
long i = st.get(0);
wins = 1;
st.remove(0);
st.add(i);
}
}
System.out.println(st.get(0));
}
}
| JAVA |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class TableTennis implements Runnable
{
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
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()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
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 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 double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
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 boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception
{
new Thread(null, new TableTennis(),"TableTennis",1<<27).start();
}
// **just change the name of class from Main to reuquired**
public void run()
{
InputReader sc = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n=sc.nextInt();
long k=sc.nextLong();
int a[]= new int[n];
for(int i=0;i<n;++i) a[i]=sc.nextInt();
int maxTillNow[]= new int[n];
maxTillNow[1]=a[0];
for(int i=2;i<n;++i)
{
maxTillNow[i]=Math.max(maxTillNow[i-1],a[i-1]);
}
int ans=-1;
for(int i=0;i<n;++i)
{
if(a[i]>maxTillNow[i])
{
int currPower=a[i];
int counter=1;
if(i==0) counter--;
for(int j=1;j<n;++j)
{
if(currPower>a[(i+j)%n]) counter++;
else break;
if(counter>=k || counter>=n-1) break;
}
if(counter>=k || counter>=n-1)
{
ans=currPower;
break;
}
}
}
w.println(ans);
System.out.flush();
w.close();
}
} | JAVA |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | n,k=map(int,input().split())
a=list(map(int,input().split()))
if k>=n:
print(max(a))
else:
for i in range(k-1):
a.append(a[i])
if max(a[0:k+1])==a[0]:
print(a[0])
else:
i=a.index(max(a[0:k+1]))
while True:
ma=max(a[i:i+k])
if ma==a[i]:
print(ma)
break
else:
i=a.index(ma)
| PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | from queue import Queue
import sys as os
n, k = map(int, input().split())
m = list(map(int, input().split()))
max = max(m)
q = Queue()
c = 0
el = m[0]
for i in m[1:]:
if i == max:
break
if el > i:
c+=1
else:
el = i
c = 1
if c == k:
print(el)
os.exit()
print(max)
| PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const double pi = acos(-1.0);
const double eps = 1e-9;
const int N = 1e6 + 10;
const int M = 1e3 + 10;
const long long mod = 1e9 + 7;
const long long inf = 1e18;
const double f = 0.32349;
int a[N];
void solve() {
ios::sync_with_stdio(false), cin.tie(0);
long long n, k;
cin >> n >> k;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
long long ans = a[0], id = 0;
for (int i = 1; i < n; i++) {
if (id >= k) {
cout << ans << '\n';
return;
}
if (ans <= a[i]) {
id = 1;
ans = a[i];
} else {
id++;
}
}
cout << ans << '\n';
}
signed main() {
solve();
return 0;
}
| CPP |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | n,k = list(map(int,input().split()))
arr = list(map(int,input().split()))
score = 0
x=0
flag = False
while score!=k:
# print("Comparing:", arr[x], "&", arr[x+1])
if arr[x] > arr[x+1]:
arr.append(arr[x+1])
arr.pop(x+1)
score += 1
if flag==True:
score += 1
if(arr[x] == max(arr)):
break
flag = False
else:
score = 0
flag = True
arr.append(arr[x])
arr.pop(x)
# print(arr)
print(arr[x])
| PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | n,k=map(int,input().split())
l=list(map(int,input().split()))
cnt=1
m=max(l[1],l[0])
for i in range(2,n):
if cnt==k:
break
if l[i]>m:
m=l[i]
cnt=1
else:
cnt+=1
print(m)
| PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | conditions = input()
nums, wins = conditions.split()
n = int(nums)
k = int(wins)
powers = input()
powersList = powers.split(' ')
powerValues = [int(x) for x in powersList]
i = 0
winCounter = []
if(k > 1000):
k = 1000
while(len(winCounter) < k):
if(powerValues[i] > powerValues[i+1]):
winCounter.append(powerValues[i+1])
powerValues.append(powerValues[i+1])
del powerValues[i+1]
elif(powerValues[i] < powerValues[i+1]):
powerValues.append(powerValues[i])
del powerValues[i]
winCounter.clear()
winCounter.append(powerValues[i+1])
print(powerValues[i])
| PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
using lli = long long;
int di[8] = {-1, 1, 0, 0, -1, 1, -1, 1};
int dj[8] = {0, 0, -1, 1, 1, 1, -1, -1};
const int N = 1.5 * 10000000 + 16;
const lli OO = 1e18;
string ys = "YES", no = "NO", st;
void fast() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
}
int main() {
fast();
int q;
q = 1;
while (q--) {
lli n, k;
cin >> n >> k;
vector<lli> v(n);
cin >> v[0];
lli mx = v[0], cnt = 0;
for (int i = 1; i < n; i++) {
cin >> v[i];
if (v[i] > mx) {
mx = v[i];
cnt = 1;
} else
cnt++;
if (cnt >= k) return cout << mx << "\n", 0;
}
cout << *max_element(v.begin(), v.end()) << "\n";
}
}
| CPP |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main
{
private InputStream is;
private PrintWriter out;
int time = 0, freq[], start[], end[], dist[], black[], MOD = (int) (1e9 + 7), arr[], weight[][], x[], y[], parent[];
int MAX = 1000001, N, K;
long red[], ans = Long.MAX_VALUE;
ArrayList<Integer>[] amp;
ArrayList<Pair>[] pmp;
boolean b[];
boolean boo[][], b1[];
Pair prr[];
HashMap<Pair, Integer> hm = new HashMap();
int Dp[][] = new int[1100][1100];
void soln()
{
is = System.in;
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
// out.close();
out.flush();
// tr(System.currentTimeMillis() - s + "ms");
}
static class ST1 // min ST
{
long arr[], st[];
int size;
ST1(long a[]) {
arr = a.clone();
size = 10 * arr.length;
st = new long[size];
build(0, arr.length - 1, 1);
}
void build(int ss, int se, int si) {
if (ss == se) {
st[si] = arr[ss];
return;
}
int mid = (ss + se) / 2;
int val = 2 * si;
build(ss, mid, val);
build(mid + 1, se, val + 1);
st[si] = Math.min(st[val], st[val + 1]);
}
void update(int ss, int se, int idx, long val, int si) {
if (ss == se) {
// if(si==idx+1)
st[si] = val;
return;
}
int mid = (ss + se) / 2;
if (ss <= idx && idx <= mid) {
update(ss, mid, idx, val, 2 * si);
} else {
update(mid + 1, se, idx, val, 2 * si + 1);
}
int v = 2 * si;
st[si] = Math.min(st[v], st[v + 1]);
}
long get(int ss, int se, int l, int r, int si) {
if (l > se || r < ss || l > r)
return Long.MAX_VALUE / 1000;
if (l <= ss && r >= se)
return st[si];
int mid = (ss + se) / 2;
int val = 2 * si;
return Math.min(get(ss, mid, l, r, val), get(mid + 1, se, l, r, val + 1));
}
}
public static void main(String[] args) throws Exception
{
new Thread(null, new Runnable()
{
public void run()
{
try
{
// new CODEFORCES().soln();
} catch (Exception e)
{
System.out.println(e);
}
}
}, "1", 1 << 26).start();
new Main().soln();
}
int D[][];
char ch[][], ch1[];
int hash = 29;
int x2, y2;
HashSet<Integer>[] hs = (HashSet<Integer>[]) new HashSet[110];
cell[] c;
Pair[] p = new Pair[4];
HashSet<String> set = new HashSet<>();
HashSet<String> dp = new HashSet<>();
private void solve()
{
int n = ni();
long k = nl();
int arr[] = na(n);
int prefix[] = new int[n];
int max = arr[0];
for(int i = 1; i< n; i++) {
if(arr[i]>max) {
max = arr[i];
prefix[i] = 1;
}
else prefix[i] = (prefix[i-1]+1);
if(prefix[i]>=k) {
System.out.println(max);
return;
}
}
System.out.println(n);
}
void bfs(int s, int n) {
b = new boolean[n];
dist = new int[n];
Arrays.fill(dist, 1000000);
dist[s] = 0;
b[s] = true;
Queue<Integer> q = new LinkedList<>();
q.add(s);
while(!q.isEmpty()) {
int y = q.poll();
for(int i : amp[y]) {
dist[i] = min(dist[i],dist[y]+1);
if(!b[i]) {
b[i] = true;
q.add(i);
}
}
}
}
boolean check(String s, String s1) {
char ch1[] = s.toCharArray(), ch2[] = s1.toCharArray();
int arr[] = new int[10];
for(char c : ch1) {
arr[c-'0']++;
}
int ans = 0;
for(char c:ch2) {
arr[c-'0']--;
}
for(int i:arr) ans += ((i>0)?i:0);
return ans==3;
}
void seive(int n)
{
start = new int[n];
for(int i = 2;i<n;i++) {
if(start[i]==0) {
for(int j = 2*i;j<n;j+=i) {
start[j] = i;
}
}
}
}
void print(int[][] arr)
{
int seed = 110, n = arr.length - 220;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i + seed][j + seed] + " ");
}
System.out.println();
}
System.out.println();
}
class cell implements Comparable<cell>
{
int s, d, p, i;
cell(int t, int d, int p, int i) {
this.s = t;
this.p = p;
this.d = d;
this.i = i;
}
public int compareTo(cell other) {
// return Integer.compare(val, other.val);
return Long.compare(d, other.d) != 0 ? (Long.compare(d, other.d)): (Long.compare(i,other.i));
// other.v));//((Long.compare(u, other.u) != 0 ? (Long.compare(u, other.u)):
// (Long.compare(v, other.v)))
// &(Long.compare(u, other.v) != 0 ? (Long.compare(u, other.v)):
// (Long.compare(v, other.u))));
}
public String toString() {
return this.d + " " + this.s +" "+this.p+" "+this.i;
}
}
int abs(int x)
{
return ((x > 0) ? x : -x);
}
long ret(int p)
{
if (p >= 0)
return 0;
else
return 1;
}
long val(int p, int a, int b)
{
if (p >= 0) {
return (a * 1l * p);
}
return (b * 1l * p);
}
void ternary_search(int l, int r)
{
// System.out.println(l+" "+r+" "+ans);
// for(int i : arr) System.out.print(i+" ");
// System.out.println();
if (r >= l) {
int mid1 = l + (r - l) / 3;
int mid2 = r - (r - l) / 3;
long cnt1 = 0, cnt2 = 0;
cnt1 = compute(mid1);
cnt2 = compute(mid2);
// System.out.println(mid1+" "+ cnt1+" "+mid2+" "+cnt2);
ans = Math.min(cnt1, cnt2);
if (cnt1 < cnt2) {
ternary_search(l, mid2 - 1);
} else {
ternary_search(mid1 + 1, r);
}
}
return;
}
long compute(int x)
{
long ans = 0;
int c = arr[0];
for (int i = 1; i <= x; i++) {
ans += max(c + 1 - arr[i], 0);
c = max(c + 1, arr[i]);
}
int temp = arr[x];
arr[x] = max(c + 1, arr[x]);
// SSystem.out.println(arr[x]+" "+ans);
c = arr[arr.length - 1];
for (int i = arr.length - 1; i > x; i--) {
ans += max(c + 1 - arr[i - 1], 0);
c = max(c + 1, arr[i - 1]);
}
arr[x] = temp;
return ans;
}
public int getParent(int x)
{
while (parent[x] != x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
void getFactors(int n, int x)
{
for (int i = 1; i * i <= n; i++) {
if (n % i == 0) {
hs[x].add(i);
hs[x].add(n / i);
}
}
}
void recur(int a, int b, int k)
{
if (k == 0) {
if (a == x2 && b == y2)
ans++;
return;
}
recur(a, b + 1, k - 1);
recur(a, b - 1, k - 1);
recur(a + 1, b, k - 1);
recur(a - 1, b, k - 1);
}
int min(int a, int b)
{
return (a < b) ? a : b;
}
/*private class Cell implements Comparable<Cell> {
int u, v, s;
public Cell(int u, int v, int s) {
this.u = u;
this.v = v;
this.s = s;
}
public int hashCode() {
return Objects.hash();
}
public int compareTo(Cell other) {
return (Long.compare(s, other.s) != 0 ? (Long.compare(s, other.s))
: (Long.compare(v, other.v) != 0 ? Long.compare(v, other.v) : Long.compare(u, other.u)))
& ((Long.compare(s, other.s) != 0 ? (Long.compare(s, other.s))
: (Long.compare(u, other.v) != 0 ? Long.compare(u, other.v) : Long.compare(v, other.u))));
}
public String toString() {
return this.u + " " + this.v;
}
}*/
class Pair implements Comparable<Pair>
{
int u ,v,i;
Pair(int u, int v) {
this.u = u;
this.i = v;
}
Pair(int u, int v, int i) {
this.u = u;
this.v = v;
this.i = i;
}
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(val, other.val);
return Long.compare(u, other.u) != 0 ? (Long.compare(u, other.u)) : (Long.compare(i, other.i));// ((Long.compare(u,
}
public String toString() {
return this.u + " " + this.v +" "+this.i;
}
}
int max(int a, int b)
{
if (a > b)
return a;
return b;
}
static class FenwickTree
{
int[] array; // 1-indexed array, In this array We save cumulative
// information to perform efficient range queries and
// updates
public FenwickTree(int size) {
array = new int[size + 1];
}
public int rsq(int ind) {
assert ind > 0;
int sum = 0;
while (ind > 0) {
sum += array[ind];
// Extracting the portion up to the first significant one of the
// binary representation of 'ind' and decrementing ind by that
// number
ind -= ind & (-ind);
}
return sum;
}
public int rsq(int a, int b) {
assert b >= a && a > 0 && b > 0;
return rsq(b) - rsq(a - 1);
}
public void update(int ind, int value) {
assert ind > 0;
while (ind < array.length) {
array[ind] += value;
// Extracting the portion up to the first significant one of the
// binary representation of 'ind' and incrementing ind by that
// number
ind += ind & (-ind);
}
}
public int size() {
return array.length - 1;
}
}
void buildGraph(int n)
{
for (int i = 0; i < n; i++) {
int x1 = ni(), y1 = ni(), z = ni();
//pmp[x1].add(new Pair(y1, z));
}
}
long modInverse(long a, long mOD2)
{
return power(a, mOD2 - 2, mOD2);
}
long power(long x, long y, long m)
{
if (y == 0)
return 1;
long p = power(x, y / 2, m) % m;
p = (p * p) % m;
return (y % 2 == 0) ? p : (x * p) % m;
}
public long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static class ST
{
int arr[], lazy[], n;
ST(int a) {
n = a;
arr = new int[10 * n];
lazy = new int[10 * n];
}
void up(int l, int r, int val) {
update(0, n - 1, 0, l, r, val);
}
void update(int l, int r, int c, int x, int y, int val) {
if (lazy[c] != 0) {
lazy[2 * c + 1] += lazy[c];
lazy[2 * c + 2] += lazy[c];
if (l == r)
arr[c] += lazy[c];
lazy[c] = 0;
}
if (l > r || x > y || l > y || x > r)
return;
if (x <= l && y >= r)
{
lazy[c] += val;
return;
}
int mid = l + r >> 1;
update(l, mid, 2 * c + 1, x, y, val);
update(mid + 1, r, 2 * c + 2, x, y, val);
arr[c] = Math.max(arr[2 * c + 1], arr[2 * c + 2]);
}
int an(int ind) {
return ans(0, n - 1, 0, ind);
}
int ans(int l, int r, int c, int ind) {
if (lazy[c] != 0) {
lazy[2 * c + 1] += lazy[c];
lazy[2 * c + 2] += lazy[c];
if (l == r)
arr[c] += lazy[c];
lazy[c] = 0;
}
if (l == r)
return arr[c];
int mid = l + r >> 1;
if (mid >= ind)
return ans(l, mid, 2 * c + 1, ind);
return ans(mid + 1, r, 2 * c + 2, ind);
}
}
public static int[] shuffle(int[] a, Random gen)
{
for (int i = 0, n = a.length; i < n; i++) {
int ind = gen.nextInt(n - i) + i;
int d = a[i];
a[i] = a[ind];
a[ind] = d;
}
return a;
}
long power(long x, long y, int mod)
{
long ans = 1;
while (y > 0) {
if (y % 2 == 0) {
x = (x * x) % mod;
y /= 2;
} else {
ans = (x * ans) % mod;
y--;
}
}
return ans;
}
// 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 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.ArrayDeque;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Aeroui
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(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, Scanner in, PrintWriter out) {
int max = -1;
int n = in.nextInt();
long k = in.nextLong();
int[] arr = new int[n];
ArrayDeque<Integer> q = new ArrayDeque<>();
for (int i = 0; i < n; ++i) {
arr[i] = in.nextInt();
max = Math.max(arr[i], max);
q.addLast(arr[i]);
}
if (k >= n) out.println(max);
else {
int cnt = 0;
int cur = q.pollFirst();
while (cnt < k) {
int curr = q.pollFirst();
if (cur > curr) {
++cnt;
q.addLast(curr);
} else {
q.add(cur);
cur = curr;
cnt = 1;
}
}
out.println(cur);
}
}
}
}
| JAVA |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | from collections import deque
def ping_pong(wins, players):
p = deque(players)
idx = 0
while idx < len(p):
win_count = 0
# has_fought handles cases where wins are > 10000000
has_fought = []
fight_count = 0
while True:
fight_count += 1 # handles edge case
if(p[0] > p[1]):
"""
the case is usually:
all players lose until you reach the biggest number
1 2 3 4 5
and that number is the winner, but in the case of
1 4 3 5 2 where wins = 2
you might expect 5 to be the expected output
but it's 4.
4 wins against 1 and it wins against 3.
"""
if fight_count == 1 and p[0] > p[-1]:
win_count += 2
else:
win_count += 1
has_fought.append(p[1])
if win_count == wins or (len(has_fought) + 1 == len(p) and max(p) == p[0]):
print(p[0])
return
else:
temp = p[1]
p.remove(temp)
p.append(temp)
else:
val = p.popleft()
p.append(val)
break
idx += 1
def main():
first_line = [int(x) for x in input().split(' ')]
second_line = [int(x) for x in input().split(' ')]
ping_pong(first_line[1], second_line)
main() | PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
/**
* Created by ndzamukashvili on 11/1/2017.
*/
public class Contest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long k = sc.nextLong();
int [] pow = new int[n];
ArrayList<Integer> list = new ArrayList<>();
for(int i=0; i<n; i++){
pow[i] = sc.nextInt();
list.add(pow[i]);
}
if(n < k){
System.out.println(max(pow));
return;
}
int [] wins = new int[n];
while (true){
int k1 = list.get(0);
int k2 = list.get(1);
if(k1 > k2){
if(list.size() > 2){
list.remove(1);
list.add(k2);
}
wins[k1-1]++;
if(wins[k1-1]==k){
System.out.println(k1);
return;
}
} else {
list.remove(0);
list.add(k1);
wins[k2-1]++;
if(wins[k2-1]==k){
System.out.println(k2);
return;
}
}
}
}
private static int max(int [] arr){
int max = -1;
for (int i=0; i<arr.length; i++){
if(max<arr[i]){
max = arr[i];
}
}
return max;
}
}
| JAVA |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | import java.util.*;
import java.io.*;
public final class Main {
public static void main(String[] args) throws Exception {
PrintWriter pw = new PrintWriter(System.out);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
Long k = Long.parseLong(st.nextToken());
Queue<Integer> list = new LinkedList<>();
st = new StringTokenizer(br.readLine());
while(st.hasMoreTokens()){
list.add(Integer.parseInt(st.nextToken()));
}
long numBeat = 0;
int currVictor = list.remove();
Set<Integer> beatSet = new HashSet<>();
while(true){
int currChallenger = list.remove();
if(beatSet.contains(currChallenger) || numBeat == k){
System.out.print(currVictor);
return;
}
if(currVictor > currChallenger){
++numBeat;
beatSet.add(currChallenger);
list.add(currChallenger);
}else{
list.add(currVictor);
beatSet.clear();
beatSet.add(currVictor);
currVictor = currChallenger;
numBeat = 1;
}
}
}
} | JAVA |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | n,k = map(int,input().split())
A = list(map(int,input().split()))
l = 0
k1 = 0
p = 0
while k1 != k and p != n:
g1 = A[l]
l += 1
g2 = A[l]
w = max(g1,g2)
A[l] = w
A.append(min(g1,g2))
if w == p:
k1 += 1
else:
p = w
k1 = 1
print(p) | PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import java.util.Map.Entry;
public class abc {
static int[] parent;
static long[] size;
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String[] ss=br.readLine().trim().split(" ");
int n=Integer.parseInt(ss[0]);
long k=Long.parseLong(ss[1]);
int[] arr=new int[n];
ss=br.readLine().trim().split(" ");
for(int i=0 ; i<arr.length ; i++) {
arr[i]=Integer.parseInt(ss[i]);
}
int count=0,max=arr[0];
for(int i=1 ; i<arr.length ; i++) {
if(max>arr[i]) {
count++;
if(count==k) {
break;
}
}else {
max=arr[i];
count=1;
}
}
System.out.println(max);
}
} | JAVA |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | import os
import sys
from io import BytesIO, IOBase
from collections import deque
n, k, a = [None] * 3
def getInput() -> None:
global n, k, a
n, k = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
def main() -> None:
getInput()
global n, k, a
d = deque(a)
prevWinner = a[0]
winCount = 0
for times in range(2 * n):
x, y= d[0], d[1]
d.popleft()
d.popleft()
if x > y:
winCount += 1
d.append(y)
d.appendleft(x)
prevWinner = x
else:
winCount = 1
d.append(x)
d.appendleft(y)
prevWinner = y
if winCount >= k:
print(prevWinner)
exit(0)
print(max(d))
#Don't go below
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
| PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int main(int argc, char* argv[]) {
int n, x, a, ans;
long long k;
scanf("%d %I64d", &n, &k);
if (k > n) k = n;
n--;
scanf("%d", &ans);
x = k;
while (n--) {
scanf("%d", &a);
if (x > 0) {
ans = max(ans, a);
if (ans == a) {
x = k - 1;
} else {
x--;
}
}
}
printf("%d\n", ans);
return 0;
}
| CPP |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | import java.io.*;
import java.util.StringTokenizer;
public class Main {
static MyScanner in;
static PrintWriter out;
public static void main(String[] args) throws IOException {
in = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out), false);
int n = in.nextInt();
long k = in.nextLong();
int[] arr = in.nextInts(n);
int max = arr[0];
int cnt = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
cnt = 1;
} else {
cnt++;
}
if (cnt == k)
break;
}
System.out.println(max);
}
}
class MyScanner implements Closeable {
public static final String CP1251 = "cp1251";
private final BufferedReader br;
private StringTokenizer st;
private String last;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public MyScanner(String path) throws IOException {
br = new BufferedReader(new FileReader(path));
}
public MyScanner(String path, String decoder) throws IOException {
br = new BufferedReader(new InputStreamReader(new FileInputStream(path), decoder));
}
public void close() throws IOException {
br.close();
}
public String next() throws IOException {
while (st == null || !st.hasMoreElements())
st = new StringTokenizer(br.readLine());
last = null;
return st.nextToken();
}
public String next(String delim) throws IOException {
while (st == null || !st.hasMoreElements())
st = new StringTokenizer(br.readLine());
last = null;
return st.nextToken(delim);
}
public String nextLine() throws IOException {
st = null;
return (last == null) ? br.readLine() : last;
}
public boolean hasNext() {
if (st != null && st.hasMoreElements())
return true;
try {
while (st == null || !st.hasMoreElements()) {
last = br.readLine();
st = new StringTokenizer(last);
}
} catch (Exception e) {
return false;
}
return true;
}
public String[] nextStrings(int n) throws IOException {
String[] arr = new String[n];
for (int i = 0; i < n; i++)
arr[i] = next();
return arr;
}
public String[] nextLines(int n) throws IOException {
String[] arr = new String[n];
for (int i = 0; i < n; i++)
arr[i] = nextLine();
return arr;
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public int[] nextInts(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
public Integer[] nextIntegers(int n) throws IOException {
Integer[] arr = new Integer[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
public int[][] next2Ints(int n, int m) throws IOException {
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
arr[i][j] = nextInt();
return arr;
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public long[] nextLongs(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
return arr;
}
public long[][] next2Longs(int n, int m) throws IOException {
long[][] arr = new long[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
arr[i][j] = nextLong();
return arr;
}
public double nextDouble() throws IOException {
return Double.parseDouble(next().replace(',', '.'));
}
public double[] nextDoubles(int size) throws IOException {
double[] arr = new double[size];
for (int i = 0; i < size; i++)
arr[i] = nextDouble();
return arr;
}
public double[][] next2Doubles(int n, int m) throws IOException {
double[][] arr = new double[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
arr[i][j] = nextDouble();
return arr;
}
public boolean nextBool() throws IOException {
String s = next();
if (s.equalsIgnoreCase("true") || s.equals("1"))
return true;
if (s.equalsIgnoreCase("false") || s.equals("0"))
return false;
throw new IOException("Boolean expected, String found!");
}
}
| JAVA |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | from collections import deque
n, k = map(int, input().split())
a = list(map(int, input().split()))
if k >= n - 1:
print(max(a))
exit()
w = [0] * n
q = deque()
for i in range(n):
q.appendleft(i)
first = q.pop()
while True:
second = q.pop()
if a[first] < a[second]:
first, second = second, first
w[first] += 1
if w[first] == k:
print(a[first])
exit()
q.appendleft(second)
| PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | n, l = map(int, input().split())
v = list(map(int, input().split()))
occ = 0
max = v[0]
for i in range(1, n):
if max>v[i]:
occ+=1
else:
max = v[i]
occ = 1
if occ==l:
break
print(max) | PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | import sys
def sim(powers, k):
cur_num_wins = 0
while cur_num_wins < k:
if powers[0] > powers[1]:
lost = powers.pop(1)
powers.append(lost)
cur_num_wins += 1
else:
lost = powers.pop(0)
powers.append(lost)
cur_num_wins = 1
return powers[0]
def solve(powers, k):
if k > len(powers):
return max(powers)
else:
return sim(powers, k)
if __name__ == "__main__":
n, k = map(int, sys.stdin.readline().split())
powers = map(int, sys.stdin.readline().split())
print solve(powers, k)
| PYTHON |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | def solve(a,k):
co=0
x=[]
if k<len(a):
while(co<k):
if a[0]>a[1]:
te=a[1]
del a[1]
a.append(te)
else:
te=a[0]
del a[0]
a.append(te)
x.append(a[0])
if len(x)==1:
co+=1
answer=x[-1]
else:
if x[-1]==x[-2]:
co+=1
answer=x[-1]
else:
co=1
answer=x[-1]
return answer
else:
return max(a)
n,k=list(map(int,input().split()))
l=list(map(int,input().split()))
x=solve(l,k)
print(x) | PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | from collections import deque
n, k = map(int, input().split())
a = list(map(int, input().split()))
a = deque(a)
b = [0] * (n + 1)
dk = max(a)
while max(b) < k:
if a[0] ==dk:
print(dk)
exit()
if a[0] > a[1]:
b[a[0]] += 1
aa = a.popleft()
bb = a.popleft()
a.appendleft(aa)
a.append(bb)
else:
b[a[1]] += 1
aa = a.popleft()
bb = a.popleft()
a.append(aa)
a.appendleft(bb)
d = max(b)
for i in range(n + 1):
if b[i] == d:
print(i)
| PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | n, k=map(int, input().split())
p=list(map(int, input().split()))
if k>=n-1:
print(max(p))
else:
ma=max(p[0:k+1])
i=p.index(ma)+1
win=1
while True:
if p[i%n]>ma:
ma=p[i]
win=1
else:
win+=1
if win==k:
print(ma)
break
i+=1
| PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
long long int n, tmp;
long long int k, c = 0;
list<int> game;
int main() {
cin >> n >> k;
for (int i = 0; i < n; i++) {
cin >> tmp;
game.push_back(tmp);
}
while (*game.begin() != n) {
if (*game.begin() > *(++game.begin())) {
tmp = *(++game.begin());
game.erase(++game.begin());
game.push_back(tmp);
c++;
} else {
tmp = *game.begin();
game.erase(game.begin());
game.push_back(tmp);
c = 1;
}
if (c == k) {
cout << *game.begin();
return 0;
}
}
cout << n;
return 0;
}
| CPP |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | n,k = map(int, input().split())
a = list(map(int, input().split()))
if k > n:
print(max(a))
exit()
st = 0
while st < k:
if a[0] > a[1]:
st+=1
a.append(a[1])
del a[1]
else:
st = 1
a.append(a[0])
del a[0]
print(a[0]) | PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | import java.util.*;
import java.lang.*;
import java.io.*;
public class Main {
public static void main (String[] args) throws java.lang.Exception {
FastIO2 in = new FastIO2();
int n = in.ni();
long k = in.nl();
int a[] = in.gia(n);
if(k>=n-1){
int max = -2;
int index=-2;
for(int i=0;i<n;i++){
max = Math.max(max, a[i]);
}
System.out.println(max);
}
else{
int wins = 0;
int i=0;
int winner = 0;
while(wins!=k){
if(winner%n==(i+1)%n){
i++;
continue;
}
if(a[winner%n]>a[(i+1)%n]){
wins++;
}
else{
wins=1;
winner = i+1;
}
i++;
}
System.out.println(a[winner%n]);
}
}
}
class FastIO2 {
private final BufferedReader br;
private String s[];
private int index;
public FastIO2() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
s = br.readLine().split(" ");
index = 0;
}
public int ni() throws IOException {
return Integer.parseInt(nextToken());
}
public double nd() throws IOException {
return Double.parseDouble(nextToken());
}
public long nl() throws IOException {
return Long.parseLong(nextToken());
}
public String next() throws IOException {
return nextToken();
}
public String nli() throws IOException {
return br.readLine();
}
public int[] gia(int n) throws IOException {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
public int[] gia(int n, int start, int end) throws IOException {
validate(n, start, end);
int a[] = new int[n];
for (int i = start; i < end; i++) {
a[i] = ni();
}
return a;
}
public double[] gda(int n) throws IOException {
double a[] = new double[n];
for (int i = 0; i < n; i++) {
a[i] = nd();
}
return a;
}
public double[] gda(int n, int start, int end) throws IOException {
validate(n, start, end);
double a[] = new double[n];
for (int i = start; i < end; i++) {
a[i] = nd();
}
return a;
}
public long[] gla(int n) throws IOException {
long a[] = new long[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
public long[] gla(int n, int start, int end) throws IOException {
validate(n, start, end);
long a[] = new long[n];
for (int i = start; i < end; i++) {
a[i] = ni();
}
return a;
}
private String nextToken() throws IndexOutOfBoundsException, IOException {
if (index == s.length) {
s = br.readLine().split(" ");
index = 0;
}
return s[index++];
}
private void validate(int n, int start, int end) {
if (start < 0 || end >= n) {
throw new IllegalArgumentException();
}
}
}
| JAVA |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | from collections import deque
n, k = map(int, input().split())
list1 = list(map(int, input().split()))
if k >= n:
print(max(list1))
else:
win = 0
winer = list1[0]
flag = True
while win < k:
if list1[0] < list1[1]:
list1.append(list1[0])
list1.pop(0)
winer = list1[0]
win = 1
else:
win += 1
list1.append(list1[1])
list1.pop(1)
print(winer) | PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | getInput = input().split()
numWins = int(getInput[1])
numPlayers = int(getInput[0])
playerPower = input().split()
Power = []
for i in playerPower:
Power.append(int(i))
countWin = 0
if len(Power) <= 3:
print(max(Power))
elif Power.index(max(Power)) < numWins:
print(max(Power))
else:
while countWin != numWins:
if Power[0] > Power[1]:
Power.append(Power.pop(1))
countWin += 1
else:
Power.append(Power.pop(0))
if countWin > 0:
countWin = 1
else:
countWin = 1
print(Power[0]) | PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | a=input().split(' ')
n=int(a[0])
k=int(a[1])
a=input().split(' ')
a=[int(i) for i in a]
if k>n-1:
print(max(a))
exit()
wf=0
c=0
cw=a[0]
for i in range(1,n-1):
cw=max(cw,a[i])
if a[i]==cw:
c=1
continue
c=c+1
if c>=k:
wf=cw
print(wf)
break
else:
print(max(a))
| PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
long long k;
cin >> n >> k;
long long a[n];
long long b[n];
for (int i = 0; i < n; i++) {
cin >> a[i];
b[i] = a[i];
}
sort(b, b + n);
long long mx = b[n - 1];
long long count = 0;
for (int i = 0; i < n; i++) {
if (a[i] == mx) {
cout << a[i] << endl;
return 0;
} else {
for (int j = i + 1; j < n; j++) {
if (a[i] > a[j]) {
count++;
if (count == k) {
cout << a[i] << endl;
return 0;
}
} else {
count = 1;
break;
}
}
}
}
}
| CPP |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | import java.io.*;
import java.util.*;
import java.math.*;
import static java.lang.Math.*;
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.Double.parseDouble;
import static java.lang.String.*;
public class Main {
public static void main(String[] args) throws IOException {
//BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//(new FileReader("input.in"));
StringBuilder out = new StringBuilder();
// PrintWriter p = new PrintWriter(System.out);
StringTokenizer tk;
Reader.init(System.in);
int n=Reader.nextInt();
long k=Reader.nextLong();
ArrayList<Integer>a=new ArrayList<>();
int max=0;
for (int i = 0; i < n; i++) {
a.add(Reader.nextInt());
max=Math.max(a.get(i),max);
}
if(k>n){
System.out.println(max);
return;
}
int maxSc=a.remove(0),maxT=0,tempS=0;
a.add(maxSc);
for (int i = 0; i < n; i++) {
if(a.size()>0){
if(maxSc>a.get(0)){
maxT++;
int x=a.remove(0);
a.add(x);
if(maxT>=(int)k){
System.out.println(maxSc);
return;
}
}
else {
a.add(maxSc);
maxSc=a.remove(0);
maxT=1;
}
}
// System.out.println(a);
/*
4 4
5 1 2 3 6
*/
}
System.out.println(max);
}
}
class pair implements Comparable<pair>{
int x,y;
public pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(pair t) {return (x+y)-(t.x+t.y);}
}
class Reader {
static StringTokenizer tokenizer;
static BufferedReader reader;
public static void init(InputStream input) throws UnsupportedEncodingException {
reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
tokenizer = new StringTokenizer("");
}
public static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
public static String nextLine() throws IOException {
return reader.readLine();
}
public static int nextInt() throws IOException {
return Integer.parseInt(next());
}
public static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public static long nextLong() throws IOException {
return Long.parseLong(next());
}
} | JAVA |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | n,k = [int(i) for i in input().split()]
l = [int(i) for i in input().split()]
d = l[0]
t = 0
for i in range(1,n):
if l[i] < d:
t = t+1
else:
t = 1
d = l[i]
if t == k:
break
print(d)
# Made By Mostafa_Khaled | PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | from sys import stdin,stdout
from collections import Counter
from itertools import permutations
import bisect
import math
I=lambda: map(int,stdin.readline().split())
I1=lambda: stdin.readline()
#(a/b)%m =((a%m)*pow(b,m-2)%m)%m
# for odered set :)
def unique(sequence):
seen = set()
return [x for x in sequence if not (x in seen or seen.add(x))]
#for _ in range(int(I1())):
n,k=I()
a=list(I())
if k>=n:
print(max(a))
exit()
i,j=0,1
w=[0]*(n+1)
while True:
if a[i]>a[j]:
x=a[j]
a.remove(x)
a.append(x)
w[a[i]]+=1
if w[a[i]]==k:
print(a[i])
exit()
else :
x=a[i]
w[a[j]]+=1
if w[a[j]]==k:
print(a[j])
exit()
a.remove(x)
a.append(x)
| PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | from Queue import Queue
def getWinner(n, k, A):
Q = Queue()
if k >= n: k = n-1
# print "k = ", k
for elem in A: Q.put(elem)
stay = Q.get()
wins = 0
while not Q.empty():
new = Q.get()
if stay > new:
# print stay, " beat ", new
wins += 1
# print "wins = ", wins
Q.put(new)
if wins >= k:
return stay
else:
# print new, " beat ", stay
Q.put(stay)
stay = new
wins = 1
return -1
[n, k] = map(int, raw_input().split())
a = map(int, raw_input().split())
print getWinner(n, k, a) | PYTHON |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) {
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
// Start writing your solution here. -------------------------------------
/*
int n = sc.nextInt(); // read input as integer
long k = sc.nextLong(); // read input as long
double d = sc.nextDouble(); // read input as double
String str = sc.next(); // read input as String
String s = sc.nextLine(); // read whole line as String
int result = 3*n;
out.println(result); // print via PrintWriter
*/
int n = sc.nextInt();
long k = sc.nextLong();
LinkedList<Integer> ll = new LinkedList<Integer>();
for(int i = 0; i <n;i++){
ll.add(sc.nextInt());
}
long wins = 0;
while(wins < k){
if(wins > 510)
break;
int a = ll.get(0);
int b = ll.get(1);
int temp;
if(a > b)
{
wins++;
temp = ll.remove(1);
ll.offer(temp);
}
else{
wins=1;
temp = ll.remove(0);
ll.offer(temp);
}
}
out.println(ll.get(0));
// Stop writing your solution here. -------------------------------------
out.close();
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
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 nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//--------------------------------------------------------
} | JAVA |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const double pi = acos(-1.0);
const double eps = 1e-9;
const long long inf = 1e18;
int toint(string s) {
int sm;
stringstream ss(s);
ss >> sm;
return sm;
}
long long tolint(string s) {
long long sm;
stringstream ss(s);
ss >> sm;
return sm;
}
long long a, b, c, d, e, f, g, h, l, m, n, p, k, q, r, t, u, v, w, x, y, z,
ara[100005] = {0}, arr[100005] = {0};
string s;
int main() {
cin.tie(0);
cout.sync_with_stdio(0);
cin >> n >> k;
for (int i = 1; i <= (n); i++) cin >> ara[i];
if (k >= n - 1) {
cout << n;
return 0;
}
if (n == 2 || n == 3) {
cout << n;
return 0;
}
deque<long long> dq;
for (int i = 1; i <= (n); i++) dq.push_back(ara[i]);
x = dq.front();
dq.pop_front();
p = 0;
while (1) {
if (dq.front() > x) {
p = 1;
dq.push_back(x);
x = dq.front();
dq.pop_front();
} else {
a = dq.front();
dq.pop_front();
dq.push_back(a);
p++;
}
if (p == k) {
cout << x;
return 0;
}
}
}
| CPP |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int main() {
long long n, k, m = LLONG_MIN;
cin >> n >> k;
queue<long long> q;
for (int i = 0; i < n; i++) {
long long v;
cin >> v;
m = max(m, v);
q.push(v);
}
long long count = 0;
long long a, b, p;
a = q.front(), q.pop(), b = q.front(), q.pop();
p = max(a, b);
count = 1;
q.push(min(a, b));
while (1) {
int t;
t = q.front(), q.pop();
if (t > p) {
count = 1;
q.push(p);
p = t;
} else {
q.push(t);
count++;
}
if (count == k) {
cout << p << endl;
return 0;
}
if (p == m) break;
}
cout << m << endl;
return 0;
}
| CPP |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | #author: riyan
if __name__ == '__main__':
n, k = map(int, input().strip().split())
arr = list(map(int, input().strip().split()))
if k >= n - 1:
ans = n
else:
i = 0
cnt = 0
ans = -1
while i < n:
if cnt == k:
ans = arr[i]
break
for j in range(i + 1, n):
if arr[i] > arr[j]:
#print('p', i, arr[i], 'p', opp, arr[opp])
cnt += 1
if cnt == k:
ans = arr[i]
break
else:
#print('rp', i, arr[i], 'rp', opp, arr[opp])
i = j
cnt = 1
break
if ans != -1:
break
if i == (n - 1):
ans = n
break
print(ans) if ans != -1 else print(n) | PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | n,k=map(int,input().split())
a=list(map(int,input().split()))
max1=max(a)
b=[]
done=False
for i in range(n):
b.append(0)
m=a.index(max1)
if(k>m):
print(max1)
else:
curr=0
for i in range(1,m):
if(a[curr]>a[i]):
#print(b)
b[curr]+=1
else:
curr=i
b[curr]+=1
if(max(b)>=k):
done=True
print(a[b.index(max(b))])
break
if(not done):
print(max1)
| PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int main() {
long long n, k;
cin >> n >> k;
vector<long long> v(n);
for (int i = 0; i < n; i++) cin >> v[i];
long long d = 0;
if (k >= n)
cout << n << endl;
else {
for (int i = 0; i < n; i++) {
for (int j = i + 1;; j++) {
if (v[i] > v[j]) {
d++;
v.push_back(v[j]);
if (d >= k) {
cout << v[i] << endl;
return 0;
}
} else {
d = 1;
v.push_back(v[i]);
i = j - 1;
break;
}
}
}
}
}
| CPP |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | import java.io.*;
import java.util.Scanner;
public class CF443 {
public static void main(String[] argc) {
final boolean isTest = false;
InputStream is = System.in;
OutputStream os = System.out;
if(isTest) {
try {
is = new FileInputStream("test/443.txt");
// os = new FileOutputStream("test/443A.out");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Scanner s = new Scanner(is);
B.solve(s);
}
static class A {
public static void solve(Scanner s, OutputStream os, int n) {
int res = 0;
for(int i = 0; i < n ; ++i) {
int a = s.nextInt();
int d = s.nextInt();
if(res == 0) {
res = a;
} else {
int k = (int) Math.ceil((res - a+ 1)*1.0/d) + 1;
res = a + (k - 1)*d;
}
}
System.out.println(res);
}
}
static class B {
public static void solve(Scanner s) {
int n = s.nextInt();
long k = s.nextLong();
int a = s.nextInt();
int b = s.nextInt();
int max = Math.max(a, b);
long end_idx = Math.min(n,k + 1);
for(int i = 2; i < end_idx ; ++i) {
int v = s.nextInt();
if(v > max) {
end_idx = Math.min(i + k , n);
max = v;
}
}
System.out.println(max);
}
}
}
| JAVA |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | import java.io.*;
import java.util.*;
import java.math.*;
public class B {
public static void main(String args[]) {
try {
InputReader in = new InputReader(System.in);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
int n = in.readInt();
long k = in.readLong();
int power[] = new int[n];
int maxPow = -1;
for (int i = 0; i < n; i++) {
power[i] = in.readInt();
maxPow = Math.max(maxPow, power[i]);
}
Queue<Integer> line = new LinkedList<>();
for (int i = 0; i < n; i++) {
line.add(power[i]);
}
int consecutiveWins = 0;
int ans = -1;
int a = line.poll();
int b = line.poll();
if (a > b) {
consecutiveWins = 1;
line.add(b);
ans = a;
}
else {
consecutiveWins = 1;
ans = b;
line.add(a);
}
while(!line.isEmpty()) {
int c = line.poll();
if (ans > c) {
consecutiveWins++;
line.add(c);
}
else {
consecutiveWins = 1;
line.add(ans);
ans = c;
}
if (consecutiveWins == k || ans == maxPow) {
break;
}
}
out.write(Integer.toString(ans));
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class InputReader {
private boolean finished = false;
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 (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 peek() {
if (numChars == -1)
return -1;
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
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 long readLong() {
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 String readString() {
int length = readInt();
if (length < 0)
return null;
byte[] bytes = new byte[length];
for (int i = 0; i < length; i++)
bytes[i] = (byte) read();
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
return new String(bytes);
}
}
public static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuffer buf = new StringBuffer();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines)
return readLine();
else
return readLine0();
}
public BigInteger readBigInteger() {
try {
return new BigInteger(readString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1)
read();
return value == -1;
}
public String next() {
return readString();
}
public boolean readBoolean() {
return readInt() == 1;
}
}
| JAVA |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | n, k = map(int, input().split())
lst = list(map(int, input().split()))
if k >= n-1:
print(max(lst))
else:
cnt = 0
temp = lst[0]
while(True):
if temp > lst[1]:
cnt += 1
lst.append(lst[1])
lst.pop(1)
else:
lst.append(temp)
lst.pop(0)
temp = lst[0]
cnt = 1
if(cnt == k):
print(temp)
break
| PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int main() {
long long int n, k;
cin >> n >> k;
long long int arr[n];
for (int i = 0; i < n; i++) cin >> arr[i];
if (k >= n - 1) {
sort(arr, arr + n);
cout << arr[n - 1];
} else {
list<long long int> q;
long long int pos = 1;
long long int cnt = 0;
q.push_back(arr[0]);
while (3) {
if (pos == n) {
sort(arr, arr + n);
cout << arr[n - 1];
break;
}
if (arr[pos] < q.front()) {
cnt++;
if (cnt == k) {
cout << q.front();
break;
}
} else {
q.push_front(arr[pos]);
cnt = 1;
}
pos++;
}
}
}
| CPP |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | import java.io.*;
import java.util.*;
import java.util.function.IntFunction;
import java.util.stream.Collectors;
public class Solution {
static MyScanner sc;
private static PrintWriter out;
static long M2 = 1_000_000_000L + 7;
public static void main(String[] s) throws Exception {
StringBuilder stringBuilder = new StringBuilder();
// stringBuilder.append("100 ");
// for (int p = 0; p < 100; p++) {
// stringBuilder.append(" 30 " + p * 5 + " 0 ");
// }
if (stringBuilder.length() == 0) {
sc = new MyScanner(System.in);
} else {
sc = new MyScanner(new BufferedReader(new StringReader(stringBuilder.toString())));
}
out = new PrintWriter(new OutputStreamWriter(System.out));
initData();
solve();
out.flush();
}
private static void initData() {
}
private static void solve() throws IOException {
int n = sc.nextInt();
long r = sc.nextLong();
int[] rr = sc.na(n);
LinkedList<Integer> data = new LinkedList<>(Arrays.stream(rr).boxed().collect(Collectors.toList()));
int cur = 0;
int last = -1;
while (last != n && cur < r) {
int v1 = data.removeFirst();
int v2 = data.removeFirst();
int m1 = Math.max(v1, v2);
int m2 = Math.min(v1, v2);
if (m1 == last) {
cur++;
} else {
cur = 1;
last = m1;
}
data.addFirst(m1);
data.addLast(m2);
}
out.println(last);
}
private static long c(long from, long to) {
long res = (fact(to) * inv(from)) % M2;
return (res * inv(to - from)) % M2;
}
private static long inv(long from) {
return pow(fact(from), M2 - 2, M2);
}
private static long fact(long from) {
long r = 1;
for (int i = 1; i <= from; i++) {
r *= i;
r %= M2;
}
return r;
}
private static void solveT() throws IOException {
int t = sc.nextInt();
while (t-- > 0) {
solve();
}
}
private static long gcd(long l, long l1) {
if (l > l1) return gcd(l1, l);
if (l == 0) return l1;
return gcd(l1 % l, l);
}
private static long pow(long a, long b, long m) {
if (b == 0) return 1;
if (b == 1) return a;
long pp = pow(a, b / 2, m);
pp *= pp;
pp %= m;
return (pp * (b % 2 == 0 ? 1 : a)) % m;
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
MyScanner(BufferedReader br) {
this.br = br;
}
public MyScanner(InputStream in) {
this(new BufferedReader(new InputStreamReader(in)));
}
void findToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
String next() {
findToken();
return st.nextToken();
}
Integer[] nab(int n) {
Integer[] k = new Integer[n];
for (int i = 0; i < n; i++) {
k[i] = sc.fi();
}
return k;
}
int[] na(int n) {
int[] k = new int[n];
for (int i = 0; i < n; i++) {
k[i] = sc.fi();
}
return k;
}
long[] nl(int n) {
long[] k = new long[n];
for (int i = 0; i < n; i++) {
k[i] = sc.nextLong();
}
return k;
}
int nextInt() {
return Integer.parseInt(next());
}
int fi() {
String t = next();
int cur = 0;
boolean n = t.charAt(0) == '-';
for (int a = n ? 1 : 0; a < t.length(); a++) {
cur = cur * 10 + t.charAt(a) - '0';
}
return n ? -cur : cur;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
private static final class HLD {
private final int count;
private final IntFunction<MetricG> metricGSupplier;
private final int[] buckets;
private final int[] indexes;
private final int[] split;
private ArrayList<MetricG> data = new ArrayList<>();
private int[] parent;
ArrayList<ArrayList<Integer>> levels = new ArrayList<>();
int ct = 0;
public HLD(int n, IntFunction<MetricG> metricGSupplier) {
this.count = n;
this.metricGSupplier = metricGSupplier;
this.parent = new int[n];
this.buckets = new int[n];
this.indexes = new int[n];
this.split = new int[n];
Arrays.fill(this.buckets, -1);
}
public void put(int item, int level, int parent) {
this.parent[item] = parent;
for (int i = levels.size(); i <= level; i++) {
levels.add(new ArrayList<>());
}
levels.get(level).add(item);
ct++;
if (ct == count) {
build();
}
}
long v(int val) {
return data.get(buckets[val]).calc(0, indexes[val]);
}
long v(int f, int t) {
return data.get(buckets[f]).calc(indexes[f], indexes[t]);
}
long ct(int from, int to, LongLongFunc ft, long init) {
while (buckets[from] != buckets[to]) {
init = ft.p(init, v(from));
from = split[from];
}
return ft.p(init, v(from, to));
}
private interface LongLongFunc {
long p(long a1, long a2);
}
private void build() {
int bck = 0;
for (int k = levels.size() - 1; k >= 0; k--) {
for (int i : levels.get(k)) {
if (buckets[i] != -1) continue;
int ll = i;
int ct = 0;
int val = bck++;
while (ll >= 0 && buckets[ll] == -1) {
buckets[ll] = val;
ct++;
ll = parent[ll];
}
split[i] = ll;
int r = i;
data.add(metricGSupplier.apply(ct));
while (r != ll) {
indexes[r] = --ct;
r = parent[r];
}
}
}
}
public void put(int item, long value) {
data.get(buckets[item]).put(indexes[item], (int) value);
}
}
private interface MetricG {
long calc(int from, int to);
void put(int x, int val);
}
private static final class STree {
long[] val1;
int[] from1;
int[] to1;
long[] max1;
public STree(int c) {
int size = Integer.highestOneBit(Math.max(c, 4));
if (size != c) {
size <<= 1;
}
int rs = size << 1;
val1 = new long[rs];
from1 = new int[rs];
max1 = new long[rs];
Arrays.fill(max1, Long.MIN_VALUE);
Arrays.fill(val1, Long.MIN_VALUE);
to1 = new int[rs];
Arrays.fill(from1, Integer.MAX_VALUE);
for (int r = rs - 1; r > 1; r--) {
if (r >= size) {
from1[r] = r - size;
to1[r] = r - size;
}
from1[r / 2] = Math.min(from1[r / 2], from1[r]);
to1[r / 2] = Math.max(to1[r / 2], to1[r]);
}
}
public long max(int from, int to) {
return max(1, from, to);
}
private long max(int cur, int from, int to) {
if (cur >= val1.length) return Long.MIN_VALUE;
if (from <= from1[cur] && to1[cur] <= to) {
return max1[cur];
}
if (from1[cur] > to || from > to1[cur]) {
return Long.MIN_VALUE;
}
cur <<= 1;
return Math.max(max(cur, from, to), max(cur + 1, from, to));
}
public void put(int x, long val) {
x += val1.length >> 1;
val1[x] = val;
max1[x] = val;
addToParent(x);
}
private void addToParent(int cur) {
while (cur > 1) {
cur >>= 1;
max1[cur] = Math.max(max1[cur << 1], max1[1 + (cur << 1)]);
}
}
}
} | JAVA |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 |
def queue(list_, k):
wins = 0
while wins < k:
if int(list_[0]) > int(list_[1]):
index = 1
wins+=1
else:
index = 0
wins = 1
list_.append(list_[index])
list_.pop(index)
return list_[0]
first = input().split()
k = int(first[1])
list_ = input().split()
if k > len(list_)-1:
k = len(list_)-1
print(queue(list_, k))
| PYTHON3 |
879_B. Table Tennis | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | 2 | 8 | n, k = map(int, input().split())
a = [int(f) for f in input().split()]
b, pob = 0, a[0]
for i in range(1,n):
if pob > a[i]:
b += 1
if pob < a[i]:
pob = a[i]
b = 1
if b == k:
break
print(pob)
| PYTHON3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.