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
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:64000000000") using namespace std; const double EPS = 1e-9; const int INF = (int)(2e9 + 0.5); const int MAXN = 201000; struct DoublyLinkedList { int next[MAXN]; int prev[MAXN]; void insert(int x, int pos) { prev[x] = pos; next[x] = next[pos]; prev[next[x]] = x; next[prev[x]] = x; } void remove(int x) { next[prev[x]] = next[x]; prev[next[x]] = prev[x]; } }; struct element { int value, pos1, pos2; element(){}; element(const int& value, const int& pos1, const int& pos2) : value(value), pos1(pos1), pos2(pos2){}; bool operator<(const element& e) const { if (value == e.value) return pos1 > e.pos1; return value > e.value; } }; int n, skill[MAXN]; char ch, seq[MAXN], killed[MAXN]; priority_queue<element> q; vector<pair<int, int> > ans; int main() { scanf("%d", &n); scanf("%c", &ch); for (int i = 1; i <= n; scanf("%c", &seq[i]), ++i) ; for (int i = 1; i <= n; scanf("%d", &skill[i]), ++i) ; DoublyLinkedList l; for (int i = 1; i <= n; ++i) l.insert(i, i - 1); for (int i = 2; i <= n; ++i) if ((seq[i] == 'B' && seq[i - 1] == 'G') || (seq[i] == 'G' && seq[i - 1] == 'B')) q.push(element(abs(skill[i - 1] - skill[i]), i - 1, i)); while (!q.empty()) { element e = q.top(); q.pop(); if (killed[e.pos1] || killed[e.pos2]) continue; ans.push_back(make_pair(e.pos1, e.pos2)); killed[e.pos1] = true; killed[e.pos2] = true; int newPos1 = l.prev[e.pos1]; int newPos2 = l.next[e.pos2]; l.remove(e.pos1); l.remove(e.pos2); if (!newPos1 || !newPos2) continue; if ((seq[newPos1] == 'G' && seq[newPos2] == 'B') || (seq[newPos1] == 'B' && seq[newPos2] == 'G')) q.push(element(abs(skill[newPos1] - skill[newPos2]), newPos1, newPos2)); } printf("%d\n", (int)ans.size()); for (int i = 0; i < (int)ans.size(); printf("%d %d\n", ans[i].first, ans[i].second), ++i) ; return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
import heapq n = int(input()) line = input() t = line.count('B') if t > n / 2: t = n - t print(t) couple = [] skill = list(map(int,input().split())) for i in range(0,n-1): if line[i] != line[i+1]: t = abs(skill[i]-skill[i+1]) couple.append([t,i,i+1]) heapq.heapify(couple) answer = [] exception = [False]*n previous = [i for i in range(n-1)] latter = [i for i in range(1,n)] while couple != []: a, b, c = heapq.heappop(couple) if exception[b] or exception[c]: continue else: exception[b] = True exception[c] = True answer += [str(b+1) + ' ' + str(c+1)] if b != 0 and c != n - 1: p = previous[b - 1] l = latter[c] if line[p] != line[l]: heapq.heappush(couple,[abs(skill[p] - skill[l]), p, l]) previous[l - 1] = p latter[p] = l print('\n'.join(answer))
PYTHON3
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; char *student; int *arr; struct node { int x; int y; int val; }; std::vector<node> v; std::vector<node> out; struct edge { int v; edge *left; edge *right; }; edge *ed; bool *flag; bool comp(node &a, node &b) { return (!(a.val < b.val || (a.val == b.val && a.x < b.x))); } void make_node(int x, int y) { if (student[x] ^ student[y]) { node temp; temp.x = x; temp.y = y; temp.val = abs(arr[x] - arr[y]); v.push_back(temp); push_heap(v.begin(), v.end(), comp); } } void print() { for (std::vector<node>::iterator it = out.begin(); it != out.end(); ++it) { node temp = *it; cout << temp.x + 1 << " " << temp.y + 1 << endl; } } void select() { while (true) { int l = -1, r = -1; while (v.size() > 0) { node temp = v.front(); pop_heap(v.begin(), v.end(), comp); v.pop_back(); l = temp.x; r = temp.y; if (flag[l] || flag[r]) { l = -1; r = -1; continue; } else { flag[l] = true; flag[r] = true; out.push_back(temp); break; } } if (l == -1) break; edge *lt = ed[l].left; edge *rt = ed[r].right; if (lt != NULL) { lt->right = rt; } if (rt != NULL) { rt->left = lt; } if (lt != NULL && rt != NULL) make_node(lt->v, rt->v); } } int main() { std::cout << std::fixed << std::setprecision(10); ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; student = new char[n]; arr = new int[n]; flag = new bool[n]; string s; cin >> s; for (int i = 0; i < n; i++) { student[i] = s[i]; int x; cin >> x; arr[i] = x; flag[i] = false; } for (int i = 0; i < n - 1; i++) { make_node(i, i + 1); } ed = new edge[n]; for (int i = 0; i < n; i++) { ed[i].v = i; ed[i].left = i > 0 ? &ed[i - 1] : NULL; ed[i].right = i < n - 1 ? &ed[i + 1] : NULL; } select(); cout << out.size() << endl; print(); }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const int MAXN = 200000 + 10; struct st { int a, b; st(int A, int B) { a = A; b = B; } }; int n, num[MAXN], tree[MAXN]; char g[MAXN]; bool mark[MAXN]; vector<pair<int, int> > answer; struct cmp { bool operator()(const st &a, const st &b) { return abs(num[a.a] - num[a.b]) != abs(num[b.a] - num[b.b]) ? abs(num[a.a] - num[a.b]) < abs(num[b.a] - num[b.b]) : a.a < b.b; } }; set<st, cmp> sit; void do_add(int k, int x) { while (k <= MAXN) { tree[k] += x; k += (k & -k); } } int do_get(int k) { int ans = 0; while (k) { ans += tree[k]; k -= (k & -k); } return ans; } int find_prev(int k) { int b = 0, e = k - 1; int x = do_get(k); while (b < e) { int m = (b + e) / 2; if (do_get(m) < x) b = m + 1; else e = m; } return b; } int find_next(int k) { if (do_get(n) == do_get(k)) return 0; int b = k + 1, e = n; int x = do_get(k); while (b < e) { int m = (b + e) / 2; if (do_get(m) <= x) b = m + 1; else e = m; } return b; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf(" %c", &g[i]); for (int i = 1; i <= n; i++) scanf("%d", &num[i]); for (int i = 1; i <= n; i++) do_add(i, 1); for (int i = 1; i < n; i++) if (g[i] != g[i + 1]) sit.insert(st(i, i + 1)); while (!sit.empty()) { st h = *sit.begin(); sit.erase(sit.begin()); if (!mark[h.a] && !mark[h.b]) { mark[h.a] = mark[h.b] = 1; answer.push_back(pair<int, int>(h.a, h.b)); do_add(h.a, -1); do_add(h.b, -1); int a = find_prev(h.a); int b = find_next(h.b); if (a != 0 && b != 0 && g[a] != g[b]) sit.insert(st(a, b)); } } printf("%d\n", answer.size()); for (int i = 0; i < answer.size(); i++) printf("%d %d\n", answer[i].first, answer[i].second); return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; int main() { string str; long long int n, bef[200005], aft[200005], skill[200005]; priority_queue< pair<long long int, pair<long long int, long long int> >, vector<pair<long long int, pair<long long int, long long int> > >, greater<pair<long long int, pair<long long int, long long int> > > > q; cin >> n >> str; for (long long int i = 0; i < ((long long int)n); i++) bef[i] = i - 1; for (long long int i = 0; i < ((long long int)n); i++) aft[i] = i + 1; for (long long int i = 0; i < ((long long int)n); i++) cin >> skill[i]; for (long long int i = 0; i < ((long long int)n - 1); i++) if (str[i] != str[i + 1]) { q.push(make_pair(abs(skill[i] - skill[i + 1]), make_pair(i, i + 1))); } vector<pair<long long int, long long int> > ans; while (((long long int)q.size())) { pair<long long int, pair<long long int, long long int> > p = q.top(); long long int a = p.second.first; long long int b = p.second.second; q.pop(); if (aft[a] == -1 || aft[b] == -1) continue; ans.push_back(make_pair(a, b)); if (bef[a] != -1 && aft[b] != n) { if (str[bef[a]] != str[aft[b]]) { q.push(make_pair(abs(skill[bef[a]] - skill[aft[b]]), make_pair(bef[a], aft[b]))); } } if (bef[a] != -1) { aft[bef[a]] = aft[b]; } if (aft[b] != n) { bef[aft[b]] = bef[a]; } aft[a] = aft[b] = -1; } cout << ((long long int)ans.size()) << endl; for (long long int i = 0; i < ((long long int)((long long int)ans.size())); i++) cout << ans[i].first + 1 << " " << ans[i].second + 1 << endl; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; struct P { int a, b, c; P() {} P(int _a, int _b, int _c) : a(_a), b(_b), c(_c) {} void print() { printf("%d %d\n", a, b); } }; bool operator<(P a, P b) { if (a.c != b.c) return a.c > b.c; return a.a > b.a; } int n; char sex[200010]; int val[200010]; void input() { scanf("%d %s", &n, sex + 1); for (int i = 1; i <= n; i++) scanf("%d", val + i); } int pre[200010], nxt[200010], vis[200010]; priority_queue<P> q; void build() { for (int i = 1; i <= n; i++) pre[i] = i - 1; for (int i = 1; i <= n; i++) nxt[i] = i + 1; for (int i = 1; i < n; i++) if (sex[i] != sex[i + 1]) q.push(P(i, i + 1, abs(val[i] - val[i + 1]))); } void del(int a, int b) { vis[a] = vis[b] = 1; int x = pre[a]; int y = nxt[b]; nxt[x] = y; pre[y] = x; if (x >= 1 && y <= n && sex[x] != sex[y]) q.push(P(x, y, abs(val[x] - val[y]))); } void solve() { vector<P> sol; while (!q.empty()) { P p = q.top(); q.pop(); if (vis[p.a] || vis[p.b]) continue; sol.push_back(p); del(p.a, p.b); } printf("%d\n", (int)sol.size()); for (int i = 0; i < (int)sol.size(); i++) sol[i].print(); } int main() { input(); build(); solve(); return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.PriorityQueue; import java.util.Scanner; public class C { public static int[] a; public static int n; public static H[] s; public static boolean[] deleted; public static PriorityQueue<Pair> heap = new PriorityQueue<Pair>(); public static ArrayList<Pair> ans = new ArrayList<Pair>(); public static class Pair implements Comparable<Pair> { int first, second; int c; @Override public int compareTo(Pair arg0) { if (c == arg0.c) { return first - arg0.first; } return c - arg0.c; } public Pair(int first, int second, int c) { super(); this.first = first; this.second = second; this.c = Math.abs(c); } } public static class H { boolean boy; int left, right; int a; public H(boolean boy, int left, int right, int a) { super(); this.boy = boy; this.left = left; this.right = right; this.a = a; } public boolean isPair(H h) { return !boy && h.boy || boy && !h.boy; } } public static void del(int x) { H hx = s[x]; if (hx.left >= 0) { s[hx.left].right = hx.right; } if (hx.right >= 0) { s[hx.right].left = hx.left; } } public static void main(String[] args) throws FileNotFoundException { // Scanner in = new Scanner(new FileInputStream("input.txt")); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(System.in); // PrintWriter out = new PrintWriter(System.out); n = in.nextInt(); in.nextLine(); String s1 = in.nextLine(); a = new int[n]; deleted = new boolean[n]; for (int i=0; i < n ; i++) { a[i] = in.nextInt(); } s = new H[n]; for (int i = 0; i < n; i++) { s[i] = new H(s1.charAt(i) == 'B', i-1, i+1, a[i]); } for (int i=0; i < n-1; i++) { if (s[i].isPair(s[i+1])) { heap.add(new Pair(i, i+1, s[i].a - s[i+1].a)); } } s[0].left = -1; s[n-1].right = -1; while (!heap.isEmpty()) { Pair pair = heap.poll(); if (deleted[pair.first] || deleted[pair.second]) { continue; } ans.add(pair); int left = s[pair.first].left; int right = s[pair.second].right; deleted[pair.first] = true; deleted[pair.second] = true; del(pair.first); del(pair.second); if (left >= 0 && right >= 0 && s[left].isPair(s[right])) { heap.add(new Pair(left, right, s[left].a - s[right].a)); } } out.println(ans.size()); for (Pair pair : ans) { out.println((pair.first + 1) + " " + (pair.second + 1)); } out.close(); in.close(); } }
JAVA
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const int N = 200005; struct dancerInfo { int delta, num, num2; dancerInfo(int _delta = 0, int _num = 0, int _num2 = 0) { delta = _delta; num = _num; num2 = _num2; } bool operator<(const dancerInfo a) const { return delta < a.delta || delta == a.delta && num < a.num || delta == a.delta && num == a.num && num2 < a.num2; } }; struct ptrs { int lef, rig; ptrs(int _lef = 0, int _rig = 0) { lef = _lef; rig = _rig; } }; ptrs ptr[N]; string s; set<dancerInfo> dan; int a[N]; bool use[N]; vector<int> ansf, anss; bool ok(int i, int j) { return s[i] == 'B' && s[j] == 'G' || s[i] == 'G' && s[j] == 'B'; } int abs(int x) { return (x < 0 ? -x : x); } int main() { int n; cin >> n >> s; s = 'P' + s; use[0] = true; a[0] = 1000000000; for (int i = 1; i <= n; i++) scanf("%d", &a[i]); for (int i = 2; i <= n; i++) { ptr[i - 1].rig = i; ptr[i].lef = i - 1; if (ok(i - 1, i)) dan.insert(dancerInfo(abs(a[i] - a[i - 1]), i - 1, i)); } int frs, sec; while (dan.size()) { dancerInfo v = (*dan.begin()); dan.erase(dan.begin()); if (use[v.num] || use[v.num2] || ptr[v.num].rig != v.num2 || ptr[v.num2].lef != v.num) continue; ansf.push_back(v.num); anss.push_back(v.num2); use[v.num] = use[v.num2] = true; frs = ptr[v.num].lef; sec = ptr[v.num2].rig; ptr[frs].rig = (frs == 0 ? 0 : sec); ptr[sec].lef = (sec == 0 ? 0 : frs); if (ok(frs, sec)) dan.insert(dancerInfo(abs(a[frs] - a[sec]), frs, sec)); } cout << ansf.size() << endl; for (int i = 0; i < ansf.size(); i++) cout << ansf[i] << " " << anss[i] << endl; return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#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; } struct data { int lpos, rpos, mn_diff; pair<int, int> pr; data() {} } tree[4 * 200000 + 7]; int n, arr[200000 + 7]; char str[200000 + 7]; data build(int node, int base, int top) { data &ret = tree[node]; if (base == top) { ret.pr = make_pair(-1, -1); ret.lpos = ret.rpos = base; ret.mn_diff = 100000000; return ret; } int left, right, mid; int d; left = 2 * node; right = left + 1; mid = (base + top) / 2; data a = build(left, base, mid); data b = build(right, mid + 1, top); if (str[a.rpos] != str[b.lpos]) { d = abs(arr[a.rpos] - arr[b.lpos]); if (d <= b.mn_diff) { ret.mn_diff = d; ret.pr = make_pair(a.rpos, b.lpos); } else { ret.mn_diff = b.mn_diff; ret.pr = b.pr; } } else { ret.mn_diff = b.mn_diff; ret.pr = b.pr; } if (a.mn_diff <= ret.mn_diff) { ret.mn_diff = a.mn_diff; ret.pr = a.pr; } ret.lpos = a.lpos; ret.rpos = b.rpos; return ret; } data update(int node, int base, int top, int p) { data &ret = tree[node]; if (base > p or top < p) return tree[node]; if (base == top) { ret.lpos = ret.rpos = -1; ret.pr = make_pair(-1, -1); ret.mn_diff = 100000000; return ret; } int left, right, mid; int d; left = 2 * node; right = left + 1; mid = (base + top) / 2; data a = update(left, base, mid, p); data b = update(right, mid + 1, top, p); if (a.lpos == -1) return ret = b; if (b.lpos == -1) return ret = a; if (str[a.rpos] != str[b.lpos]) { d = abs(arr[a.rpos] - arr[b.lpos]); if (d <= b.mn_diff) { ret.mn_diff = d; ret.pr = make_pair(a.rpos, b.lpos); } else { ret.mn_diff = b.mn_diff; ret.pr = b.pr; } } else { ret.mn_diff = b.mn_diff; ret.pr = b.pr; } if (a.mn_diff <= ret.mn_diff) { ret.mn_diff = a.mn_diff; ret.pr = a.pr; } ret.lpos = a.lpos; ret.rpos = b.rpos; return ret; } int main() { int sz, i, j, k; data ret; vector<pair<int, int> > ans; scanf("%d", &n); scanf("%s", str + 1); for (i = 1; i <= n; i++) { scanf("%d", &arr[i]); } ret = build(1, 1, n); while (ret.pr.first != -1) { ans.push_back(ret.pr); update(1, 1, n, ret.pr.first); ret = update(1, 1, n, ret.pr.second); } sz = ans.size(); printf("%d\n", sz); for (i = 0; i < sz; i++) { printf("%d %d\n", ans[i].first, ans[i].second); } return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const int N = 2 * 1e5 + 5; int vis[N], ll[N], rr[N], skill[N]; struct node { int u, v, c; }; inline bool operator<(const node a, const node b) { if (a.c ^ b.c) return a.c > b.c; else return a.u > b.u; } priority_queue<node> q; int main() { int n, i, j = 0, sum = 0; char c; node z; cin >> n; getchar(); int sex[n + 1]; for (i = 1; i <= n; i++) { c = getchar(); if (c == 'B') { sex[i] = 0; sum++; } else sex[i] = 1; } sum > n - sum ? sum = n - sum : sum = sum; for (i = 1; i <= n; i++) cin >> skill[i]; for (i = 1; i <= n; i++) ll[i] = i - 1, rr[i] = i + 1; for (i = 1; i < n; i++) { if (sex[i] != sex[i + 1]) { z.u = i; z.v = i + 1; z.c = abs(skill[i] - skill[i + 1]); q.push(z); } } cout << sum << endl; while (sum--) { while (!q.empty()) { z = q.top(); q.pop(); if (!vis[z.u] && !vis[z.v]) { cout << z.u << " " << z.v << "\n"; vis[z.u] = vis[z.v] = 1; break; } } int b = ll[z.u], t = rr[z.v]; rr[b] = t; ll[t] = b; z.u = b; z.v = t; z.c = abs(skill[b] - skill[t]); if (b > 0 && t <= n && sex[b] != sex[t]) q.push(z); } return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; void solve() { long long n; cin >> n; string str; cin >> str; char ch[n + 5]; long long lvl[n + 5]; long long l[n + 5]; long long r[n + 5]; for (long long i = 1; i <= n; i++) ch[i] = str[i - 1]; for (long long i = 1; i <= n; i++) cin >> lvl[i]; for (int i = 1; i <= n; i++) { l[i] = i - 1; r[i] = i + 1; } vector<pair<long long, long long>> ans; set<pair<long long, long long>> second; for (long long i = 1; i < n; i++) { if (ch[i] != ch[i + 1]) { second.insert(make_pair(abs(lvl[i] - lvl[i + 1]), i)); } } while (second.size()) { auto it = second.begin(); long long a = it->second; long long b = r[a]; second.erase(it); ans.push_back(make_pair(a, b)); if (l[a] != 0 and ch[l[a]] != ch[a]) second.erase(make_pair(abs(lvl[l[a]] - lvl[a]), l[a])); if (r[b] != n + 1 and ch[r[b]] != ch[b]) second.erase(make_pair(abs(lvl[r[b]] - lvl[b]), b)); if (l[a] != 0 and r[b] != n + 1 and ch[l[a]] != ch[r[b]]) second.insert(make_pair(abs(lvl[l[a]] - lvl[r[b]]), l[a])); if (l[a] != -1) r[l[a]] = r[b]; if (r[b] != n + 1) l[r[b]] = l[a]; } cout << ans.size() << "\n"; for (long long i = 0; i < ans.size(); i++) cout << ans[i].first << " " << ans[i].second << "\n"; return; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); ; long long t; t = 1; while (t--) solve(); return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 10; set<pair<int, pair<int, int>>> s; set<pair<int, pair<int, int>>>::iterator it; vector<pair<int, int>> ans; int n, v[N], nex[N], last[N]; char a[N]; bool checking[N]; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); ; scanf("%d%s", &n, a + 1); for (int i = 1; i <= n; ++i) scanf("%d", &v[i]); for (int i = 1; i <= n; ++i) nex[i] = i + 1, last[i] = i - 1, checking[i] = true; for (int i = 1; i < n; ++i) { if (a[i] ^ a[i + 1]) s.insert(make_pair(abs(v[i] - v[i + 1]), make_pair(i, i + 1))); } while (s.size()) { it = s.begin(); int x = (*it).second.first; int y = (*it).second.second; s.erase(it); if (checking[x] && checking[y]) ans.push_back(make_pair(x, y)), checking[x] = checking[y] = false; else { continue; } int p = last[x]; int q = nex[y]; nex[p] = q; last[q] = p; if (p <= n && p >= 1 && q <= n && q >= 1 && a[p] ^ a[q]) { s.insert(make_pair(abs(v[p] - v[q]), make_pair(p, q))); } } cout << ans.size() << "\n"; for (int i = 0; i < ans.size(); ++i) cout << ans[i].first << " " << ans[i].second << "\n"; return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> inline int Abs(int K) { return K > 0 ? K : -K; } struct ele_t { int pA, pB, val; bool operator<(const ele_t &cmp) const { if (val != cmp.val) return val > cmp.val; else return pA > cmp.pA; } ele_t() {} ele_t(int a, int b, int c) { pA = a, pB = b, val = c; } }; struct man { int gen, nxt, pre, val; } M[200001]; int N; int ans[200001][2], ac; char line[200001]; bool use[200001]; std::priority_queue<ele_t> Q; int fst, lst; void del(int pos) { use[pos] = true; if (pos == fst) { fst = M[pos].nxt; M[M[pos].nxt].pre = -1; } else if (pos == lst) { lst = M[pos].pre; M[M[pos].pre].nxt = -1; } else { int a = M[M[pos].pre].nxt = M[pos].nxt; int b = M[M[pos].nxt].pre = M[pos].pre; if (M[a].gen != M[b].gen) Q.push(ele_t(b, a, Abs(M[b].val - M[a].val))); } return; } int main() { scanf("%d", &N); fst = 0, lst = N - 1; scanf("%s", line); for (int i = 0; i < N; i++) scanf("%d", &M[i].val); for (int i = 0; i < N - 1; i++) M[i].nxt = i + 1; for (int i = 1; i < N; i++) M[i].pre = i - 1; M[0].pre = -1; M[N - 1].nxt = -1; for (int i = 0; i < N; i++) M[i].gen = line[i] == 'B' ? 1 : 0; for (int i = 0; i < N - 1; i++) if (M[i].gen != M[i + 1].gen) Q.push(ele_t(i, i + 1, Abs(M[i].val - M[i + 1].val))); while (!Q.empty()) { ele_t now = Q.top(); Q.pop(); if (use[now.pA] || use[now.pB]) continue; del(now.pA); del(now.pB); ans[ac][0] = now.pA; ans[ac][1] = now.pB; ++ac; } printf("%d\n", ac); for (int i = 0; i < ac; i++) printf("%d %d\n", ans[i][0] + 1, ans[i][1] + 1); }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const double PI = acos(-1.0); struct debugger { template <typename T> debugger& operator,(const T& v) { cerr << v << " "; return *this; } } dbg; char gender[200005]; int prevv[200005], nextt[200005], skill[200005]; priority_queue<pair<int, int> > q; vector<pair<int, int> > couple; bool danced[200005]; int main() { int i, n, nw, pr, nx; pair<int, int> top; scanf("%d", &n); scanf("%s", gender); for (i = 0; i < n; i++) scanf("%d", &skill[i]); for (i = 0; i < n - 1; i++) { prevv[i] = i - 1; nextt[i] = i + 1; danced[i] = false; if (gender[i] != gender[i + 1]) q.push(make_pair((-1) * abs(skill[i] - skill[i + 1]), (-1) * i)); } prevv[i] = i - 1; nextt[i] = i + 1; danced[i] = false; while (!q.empty()) { top = q.top(); q.pop(); nw = top.second * (-1); pr = prevv[nw]; nx = nextt[nw]; if (nx == n || danced[nw] || danced[nx]) continue; if (abs(skill[nw] - skill[nx]) != (-1) * top.first) continue; couple.push_back(make_pair(min(nw, nx), max(nw, nx))); danced[nw] = danced[nx] = true; if (nextt[nx] != n) prevv[nextt[nx]] = pr; if (pr != -1) nextt[pr] = nextt[nx]; nx = nextt[nx]; if (pr != -1 && nx != n && gender[pr] != gender[nx]) q.push(make_pair((-1) * abs(skill[nx] - skill[pr]), (-1) * pr)); } printf("%d\n", (int)couple.size()); for (i = 0; i < couple.size(); i++) printf("%d %d\n", couple[i].first + 1, couple[i].second + 1); return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const int N = 200000; pair<int, pair<int, int> > ms(int a, int b, int c) { return make_pair(a, make_pair(b, c)); } int x[N]; char s[N + 1]; bool viz[N]; int m = 0; int l[N], r[N]; int r1[N], r2[N]; priority_queue<pair<int, pair<int, int> >, vector<pair<int, pair<int, int> > >, greater<pair<int, pair<int, int> > > > q; int main() { int n; scanf("%d", &n); scanf("%s", s); for (int i = 0; i < n; i++) cin >> x[i]; for (int i = 0; i < n - 1; i++) { l[i] = i - 1; r[i] = i + 1; if (s[i] != s[i + 1]) q.push(ms(abs(x[i + 1] - x[i]), i, i + 1)); } l[n - 1] = n - 2; r[n - 1] = n; while (!q.empty()) { pair<int, pair<int, int> > st = q.top(); q.pop(); int i = st.second.first; int j = st.second.second; if (viz[i] || viz[j]) continue; viz[i] = viz[j] = 1; r1[m] = i; r2[m] = j; m++; if (l[i] != -1) r[l[i]] = r[j]; if (r[j] != n) l[r[j]] = l[i]; if (l[i] != -1 && r[j] != n && s[l[i]] != s[r[j]]) q.push(ms(abs(x[l[i]] - x[r[j]]), l[i], r[j])); } printf("%d\n", m); for (int i = 0; i < m; i++) printf("%d %d\n", r1[i] + 1, r2[i] + 1); }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const int N = 200005; struct ptrs { int lef, rig; ptrs(int _lef = 0, int _rig = 0) { lef = _lef; rig = _rig; } }; ptrs ptr[N]; string s; set<pair<pair<int, int>, int> > dan; int a[N]; bool use[N]; vector<int> ansf, anss; bool ok(int i, int j) { return s[i] == 'B' && s[j] == 'G' || s[i] == 'G' && s[j] == 'B'; } int abs(int x) { return (x < 0 ? -x : x); } int main() { int n; cin >> n >> s; s = 'P' + s; use[0] = true; a[0] = 1000000000; for (int i = 1; i <= n; i++) scanf("%d", &a[i]); for (int i = 2; i <= n; i++) { ptr[i - 1].rig = i; ptr[i].lef = i - 1; if (ok(i - 1, i)) dan.insert(make_pair(make_pair(abs(a[i] - a[i - 1]), i - 1), i)); } int frs, sec; while (dan.size()) { pair<pair<int, int>, int> v = (*dan.begin()); dan.erase(dan.begin()); if (use[v.first.second] || use[v.second] || ptr[v.first.second].rig != v.second || ptr[v.second].lef != v.first.second) continue; ansf.push_back(v.first.second); anss.push_back(v.second); use[v.first.second] = use[v.second] = true; frs = ptr[v.first.second].lef; sec = ptr[v.second].rig; ptr[frs].rig = (frs == 0 ? 0 : sec); ptr[sec].lef = (sec == 0 ? 0 : frs); if (ok(frs, sec)) dan.insert(make_pair(make_pair(abs(a[frs] - a[sec]), frs), sec)); } cout << ansf.size() << endl; for (int i = 0; i < ansf.size(); i++) cout << ansf[i] << " " << anss[i] << endl; return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const int MOD = 1e9 + 7; const int INF = 1e9; const long long LINF = 1e18; const int WOW = 40000; const int NIL = 0; const int dy[8] = {1, 0, -1, 0, 1, 1, -1, -1}; const int dx[8] = {0, 1, 0, -1, 1, -1, 1, -1}; const double PI = 2 * acos(0); const int MAXN = 2e5 + 5; int l[MAXN], r[MAXN], N; string s; int arr[MAXN]; bool die[MAXN]; priority_queue<pair<int, pair<int, int> > > q; void del(int i, int j) { die[i] = die[j] = 1; int left = l[i], right = r[j]; if (left != -1) r[left] = right; if (right != N) l[right] = left; if (left != -1 && right != N && s[left] + s[right] == 'B' + 'G') q.push({-abs(arr[left] - arr[right]), {-left, right}}); } int main() { scanf("%d", &N); cin >> s; for (int i = 0; i < N; ++i) scanf("%d", &arr[i]); for (int i = 0; i < N; ++i) { l[i] = i - 1, r[i] = i + 1; if (i != N - 1 && s[i] + s[i + 1] == 'B' + 'G') q.push({-abs(arr[i] - arr[i + 1]), {-i, i + 1}}); } vector<pair<int, int> > ans; while (q.size()) { pair<int, pair<int, int> > e = q.top(); q.pop(); int i = -e.second.first, j = e.second.second; if (die[i] || die[j]) continue; ans.push_back({-e.second.first, e.second.second}); del(i, j); } printf("%d\n", ans.size()); for (pair<int, int> v : ans) printf("%d %d\n", v.first + 1, v.second + 1); }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
# -*- coding: utf-8 -*- """ Created on Sat May 7 10:46:00 2016 @author: Alex """ import heapq, sys n = int(input()) sex = input() r = [i+1 for i in range(n)] l = [i-1 for i in range(n)] skill = list(map(int,input().split())) result = [] answer = [] cnt = 0 for i in range(n-1): if sex[i]!=sex[i+1]: heapq.heappush(result,(abs(skill[i]-skill[i+1]),i,i+1)) cnt+=1 while cnt>0: s,i,j = heapq.heappop(result) cnt-=1 if r[i]==-1 or r[j]==-1: continue answer.append('%d %d'%(i+1,j+1)) u = l[i] v = r[j] r[i]=r[j]=-1 if u>=0: r[u]=v if v<n: l[v]=u if u>=0 and v<n and sex[u]!=sex[v]: heapq.heappush(result,(abs(skill[v]-skill[u]),u,v)) cnt+=1 sys.stdout.write(str(len(answer)) + '\n' + '\n'.join(answer) + '\n')
PYTHON3
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
import heapq as hq n=int(input()) s=input() a=list(map(int,input().split())) pre=[i-1 for i in range(n)] nxt=[i+1 for i in range(n)] free=[1 for i in range(n)] line=[(abs(a[i]-a[i+1]),i,i+1) for i in range(n-1) if s[i]!=s[i+1]] hq.heapify(line) ans=[] while line: t,ppre,pnxt=hq.heappop(line) if free[ppre] and free[pnxt]: ans.append(str(ppre+1)+' '+str(pnxt+1)) free[ppre],free[pnxt]=0,0 if ppre==0 or pnxt==n-1: continue preppre,nxtpnxt=pre[ppre],nxt[pnxt] nxt[preppre],pre[nxtpnxt]=nxtpnxt,preppre if s[preppre]!=s[nxtpnxt]: hq.heappush(line,(abs(a[preppre]-a[nxtpnxt]),preppre,nxtpnxt)) print(len(ans)) print('\n'.join(ans))
PYTHON3
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; int main() { set<int> mn, all; map<int, set<pair<int, int> > > ma; int n, i, g, x, y; cin >> n; string st; cin >> st; vector<int> a(n), b(n); for (i = 0; i < n; i++) { cin >> a[i]; } vector<pair<int, int> > c; for (i = 0; i < n; i++) { all.insert(i); b[i] = st[i] == 'B' ? 1 : 0; if (i && b[i] + b[i - 1] == 1) { x = abs(a[i] - a[i - 1]); mn.insert(x); ma[x].insert(make_pair(i - 1, i)); } } int m, v; pair<int, int> t; set<int>::iterator i1, i2, i3, i4, sr; while (!mn.empty() && all.size() > 1) { m = *mn.begin(); t = *ma[m].begin(); ma[m].erase(t); x = t.first; y = t.second; sr = all.end(); sr--; i1 = i3 = all.find(x); i3--; i2 = i4 = all.find(y); i4++; if (i1 != all.begin() && i1 != all.end() && i2 != sr && i2 != all.end() && b[*i3] + b[*i4] == 1) { v = abs(a[*i3] - a[*i4]); mn.insert(v); ma[v].insert(make_pair(*i3, *i4)); } if (i1 != all.begin()) { v = abs(a[*i3] - a[*i1]); ma[v].erase(make_pair(*i3, *i1)); if (ma[v].empty()) { mn.erase(v); } } if (i2 != sr) { v = abs(a[*i2] - a[*i4]); ma[v].erase(make_pair(*i2, *i4)); if (ma[v].empty()) { mn.erase(v); } } if (b[x] >= 0 && b[y] >= 0) { c.push_back(t); b[x] = b[y] = -1; all.erase(x); all.erase(y); } if (ma[m].empty()) { mn.erase(m); } } cout << c.size() << endl; for (i = 0; i < c.size(); i++) { cout << c[i].first + 1 << " " << c[i].second + 1 << endl; } return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
from heapq import heappush,heappop,heapify n=int(input()) symbols=input() skl=list(map(int,input().split())) LMap=[i-1 for i in range(n+1)] RMap=[i+1 for i in range(n+1)] LMap[1],RMap[n]=1,n h=[] res=[] cnt=0 B=symbols.count("B") N=min(n-B,B) ind=[True]*(n+1) h=[] for i in range(n-1) : if symbols[i]!=symbols[i+1] : h.append((abs(skl[i]-skl[i+1]),i+1,i+2)) heapify(h) i=0 while cnt<N : d,L,R=heappop(h) if ind[L] and ind[R] : cnt+=1 ind[L],ind[R]=False,False res.append(str(L)+" "+str(R)) if L==1 or R==n : continue L,R=LMap[L],RMap[R] RMap[L],LMap[R]=R,L if symbols[L-1]!=symbols[R-1] : heappush(h,(abs(skl[L-1]-skl[R-1]),L,R)) assert cnt==N print(cnt) print('\n'.join(res))
PYTHON3
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const int MAXN = 2 * 1000 * 100 + 10; string str; set<pair<int, pair<int, int> > > s; struct node { int pre, next, key; bool g, val; }; vector<pair<int, int> > ans; node a[MAXN]; int n; int main() { cin >> n >> str; for (int i = 0; i < n; i++) { scanf("%d", &a[i].key); a[i].pre = (i - 1); a[i].next = (i + 1); a[i].g = (str[i] == 'G') ? true : false; a[i].val = true; } for (int i = 0; i < n - 1; i++) if (str[i] != str[i + 1]) s.insert(make_pair(abs(a[i].key - a[i + 1].key), make_pair(i, i + 1))); while (!s.empty()) { if (a[(s.begin()->second.first)].val && a[(s.begin()->second.second)].val) { ans.push_back(s.begin()->second); int u, v; u = s.begin()->second.first; v = s.begin()->second.second; a[a[u].pre].next = a[v].next; a[a[v].next].pre = a[u].pre; a[u].val = false; a[v].val = false; s.erase(s.begin()); if (a[u].pre != -1 && a[v].next != n) { if (a[a[u].pre].g != a[a[v].next].g) { int k = abs(a[a[u].pre].key - a[a[v].next].key); s.insert(make_pair(k, make_pair(min(a[u].pre, a[v].next), max(a[u].pre, a[v].next)))); } } } else s.erase(s.begin()); } cout << ans.size() << endl; for (int i = 0; i < ans.size(); i++) printf("%d %d\n", ans[i].first + 1, ans[i].second + 1); return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; int n, m, L, R; int c[200000], l[200000], r[200000]; bool used[200000]; char sex[200000]; set<pair<int, pair<int, int> > > q; vector<pair<int, int> > vp; pair<int, pair<int, int> > v; int main() { scanf("%d\n", &n); for (int i = 0; i < n; i++) { scanf("%c", &sex[i]); l[i] = i - 1; r[i] = i + 1; used[i] = false; } for (int i = 0; i < n; i++) { scanf("%d", &c[i]); } for (int i = 0; i < n - 1; i++) { if (sex[i] != sex[i + 1]) q.insert(make_pair(abs(c[i] - c[i + 1]), make_pair(i, i + 1))); } while (!q.empty()) { v = *q.begin(); q.erase(q.begin()); if (!used[v.second.first] && !used[v.second.second] && r[v.second.first] == v.second.second) { vp.push_back(make_pair(v.second.first, v.second.second)); used[v.second.first] = true; used[v.second.second] = true; L = l[v.second.first]; R = r[v.second.second]; if (l[v.second.first] >= 0) r[l[v.second.first]] = r[v.second.second]; if (r[v.second.second] < n) l[r[v.second.second]] = l[v.second.first]; if (L >= 0 && R < n && sex[L] != sex[R]) q.insert(make_pair(abs(c[L] - c[R]), make_pair(L, R))); } } printf("%d\n", vp.size()); for (int i = 0; i < vp.size(); i++) { printf("%d %d\n", vp[i].first + 1, vp[i].second + 1); } return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const int N = 2e+5 + 5; int n, a[N]; char ty[N]; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> n; for (int i = 1; i <= n; i++) cin >> ty[i]; for (int i = 1; i <= n; i++) cin >> a[i]; set<pair<int, pair<int, int>>> st; set<int> elt; for (int i = 1; i < n; i++) { elt.insert(i); if (ty[i] != ty[i + 1]) { st.insert(make_pair(abs(a[i] - a[i + 1]), make_pair(i, i + 1))); } } elt.insert(n); vector<pair<int, int>> ans; while (!st.empty()) { auto it = *st.begin(); st.erase(it); ans.push_back(make_pair(it.second.first, it.second.second)); int l = -1, r = -1; auto jt = elt.lower_bound(it.second.first); if (jt != elt.begin()) { jt--; l = *jt; } if (l != -1) { auto d = make_pair(abs(a[l] - a[it.second.first]), make_pair(l, it.second.first)); if (st.find(d) != st.end()) st.erase(d); } jt = elt.upper_bound(it.second.second); if (jt != elt.end()) r = *jt; elt.erase(it.second.first); elt.erase(it.second.second); if (r != -1) { auto d = make_pair(abs(a[r] - a[it.second.second]), make_pair(it.second.second, r)); if (st.find(d) != st.end()) st.erase(d); } if (l != -1 && r != -1) { if (ty[l] != ty[r]) st.insert(make_pair(abs(a[l] - a[r]), make_pair(l, r))); } } cout << ans.size() << "\n"; for (auto it : ans) cout << it.first << " " << it.second << "\n"; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const int INF = INT_MAX; const int MAX = 200005; int a[MAX], l[MAX], r[MAX]; bool boy[MAX]; set<pair<int, int> > dif; int val(int p) { if (l[p] == -1) { if (boy[r[p]] != boy[p]) return r[p]; return -1; } if (r[p] == -1) { if (boy[l[p]] != boy[p]) return l[p]; return -1; } if (boy[l[p]] == boy[p] && boy[p] == boy[r[p]]) return -1; if (boy[l[p]] == boy[p] && boy[p] != boy[r[p]]) return r[p]; if (boy[l[p]] != boy[p] && boy[p] == boy[r[p]]) return l[p]; if (abs(a[l[p]] - a[p]) < abs(a[p] - a[r[p]])) return l[p]; return r[p]; } int main() { ios::sync_with_stdio(false); int n, b = 0, g = 0; cin >> n; for (int i = 0; i < n; i++) { l[i] = (i == 0 ? -1 : i - 1); r[i] = (i == n - 1 ? -1 : i + 1); char c; cin >> c; boy[i] = (c == 'B'); b += boy[i]; g += !boy[i]; } cout << min(b, g) << endl; for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) if (val(i) != -1) dif.insert(make_pair(abs(a[i] - a[val(i)]), i)); while (!dif.empty()) { int t1 = dif.begin()->second; dif.erase(dif.begin()); int t2 = val(t1); dif.erase(make_pair(abs(a[t2] - a[t1]), t2)); cout << min(t1, t2) + 1 << " " << max(t1, t2) + 1 << endl; int upd1, upd2; if (t1 < t2) { upd1 = l[t1]; upd2 = r[t2]; } else { upd1 = l[t2]; upd2 = r[t1]; } if (upd1 != -1 && val(upd1) != -1) dif.erase(make_pair(abs(a[upd1] - a[val(upd1)]), upd1)); if (upd2 != -1 && val(upd2) != -1) dif.erase(make_pair(abs(a[upd2] - a[val(upd2)]), upd2)); r[upd1] = upd2; l[upd2] = upd1; if (upd1 != -1 && val(upd1) != -1) dif.insert(make_pair(abs(a[upd1] - a[val(upd1)]), upd1)); if (upd2 != -1 && val(upd2) != -1) dif.insert(make_pair(abs(a[upd2] - a[val(upd2)]), upd2)); } return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; struct Mok { int skil; bool lyt; int i; bool pan = false; list<Mok *>::iterator it; }; struct Pora { int del; int i, j; Mok *a, *b; bool operator<(const Pora &o) const { if (del == o.del) return i < o.i; return del < o.del; } Pora(Mok *x, Mok *y) { i = x->i; j = y->i; del = abs(x->skil - y->skil); a = x, b = y; } }; int main() { int n; cin >> n; string a; cin >> a; list<Mok *> mok; for (int i = 0; i < n; i++) { Mok *x = new Mok; x->lyt = a[i] == 'B'; cin >> x->skil; x->i = i; mok.push_back(x); x->it = --mok.end(); } multiset<Pora> b; for (list<Mok *>::iterator i = mok.begin(); i != --mok.end(); i++) { list<Mok *>::iterator j = i; j++; if ((*i)->lyt != (*j)->lyt) b.insert(Pora(*i, *j)); } vector<pair<int, int>> ats; while (b.size() > 0) { Pora p = *b.begin(); b.erase(b.begin()); if (p.a->pan or p.b->pan) continue; ats.push_back(make_pair(p.i + 1, p.j + 1)); p.a->pan = true; p.b->pan = true; list<Mok *>::iterator i = p.a->it; list<Mok *>::iterator j = p.b->it; if (i == mok.begin() or j == --mok.end()) { mok.erase(i); mok.erase(j); continue; } i--; j++; mok.erase(p.a->it); mok.erase(p.b->it); if ((*i)->lyt != (*j)->lyt) b.insert(Pora(*i, *j)); } cout << ats.size() << "\n"; for (auto &&x : ats) cout << x.first << " " << x.second << "\n"; return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> double const EPS = 3e-8; using namespace std; template <class T> T gcd(T a, T b) { return (b != 0 ? gcd<T>(b, a % b) : a); } template <class T> T lcm(T a, T b) { return (a / gcd<T>(a, b) * b); } template <class T> inline T bigmod(T p, T e, T M) { if (e == 0) return 1; if (e % 2 == 0) { long long t = bigmod(p, e / 2, M); return (T)((t * t) % M); } return (T)((long long)bigmod(p, e - 1, M) * (long long)p) % M; } template <class T> inline T modinverse(T a, T M) { return bigmod(a, M - 2, M); } template <class T> inline bool read(T &x) { int c = getchar(); int sgn = 1; while (~c && c < '0' || c > '9') { if (c == '-') sgn = -1; c = getchar(); } for (x = 0; ~c && '0' <= c && c <= '9'; c = getchar()) x = x * 10 + c - '0'; x *= sgn; return ~c; } const int maxn = 1000005; string str; int inp[1000005], n, Left[maxn], Right[maxn]; struct node { int x, y, d; node(int x, int y, int d) : x(x), y(y), d(d) {} }; bool operator<(const node &A, const node &B) { if (A.d == B.d) { if (A.x == B.x) return A.y > B.y; return A.x > B.x; } return A.d > B.d; } priority_queue<node> pq; bool Vis[maxn]; int main() { cin >> n >> str; int i; for (i = 0; i < n; i++) cin >> inp[i], Left[i] = i - 1, Right[i] = i + 1; for (i = 0; i < n - 1; i++) { if (str[i] != str[i + 1]) pq.push(node(i, i + 1, abs(inp[i] - inp[i + 1]))); } vector<pair<int, int> > ans; while (!pq.empty()) { int x, y; x = pq.top().x; y = pq.top().y; pq.pop(); if (Vis[x] || Vis[y]) continue; Vis[x] = 1; Vis[y] = 1; ans.push_back(make_pair(x, y)); int nx = Left[x]; int ny = Right[y]; Left[ny] = nx; Right[nx] = ny; if (nx >= 0 && ny < n && str[nx] != str[ny]) { pq.push(node(nx, ny, abs(inp[nx] - inp[ny]))); } } cout << ans.size() << endl; for (i = 0; i < ans.size(); i++) { cout << ans[i].first + 1 << " " << ans[i].second + 1 << endl; } return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const long long M = 1e9 + 7, inf = 1e18; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); ; int n; string str; cin >> n >> str; int a[n]; for (int i = 0; i < n; i++) cin >> a[i]; ; set<pair<int, pair<int, int> > > s; set<int> alv; vector<pair<int, int> > ans; for (int i = 0; i < n; i++) { alv.insert(i); } for (int i = 1; i < n; i++) { if (str[i] != str[i - 1]) { s.insert({abs(a[i] - a[i - 1]), {i - 1, i}}); } } while (not s.empty()) { auto x = *s.begin(); s.erase(s.begin()); int l, r, nx = -1, pr = -1; l = x.second.first; if (alv.find(l) == alv.end()) { continue; } r = x.second.second; if (alv.find(r) == alv.end()) { continue; } auto it = alv.lower_bound(l); if (it != alv.begin()) { it = prev(it); pr = *it; } it = alv.upper_bound(r); if (it != alv.end()) { nx = *it; } alv.erase(l); alv.erase(r); ans.push_back({l, r}); if (nx != -1 and pr != -1) { if (str[pr] != str[nx]) { s.insert({abs(a[nx] - a[pr]), {pr, nx}}); } } } cout << ans.size() << "\n"; for (auto x : ans) { cout << x.first + 1 << ' ' << x.second + 1 << "\n"; ; } }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; vector<int> a; vector<bool> was; priority_queue<pair<int, pair<int, int> > > q; vector<pair<int, int> > ans; vector<int> l, r; int n; int lpred(int i) { int x = i; while (i >= 0 && was[i] == true) i = l[i]; while (x != i) { int c = x; x = l[x]; l[c] = i; } return i; }; int rpred(int i) { int x = i; while (i < n && was[i] == true) i = r[i]; while (x != i) { int c = x; x = r[x]; r[c] = i; } return i; }; int main() { string s; scanf("%d", &n); cin >> s; for (int i = 0; i < n; i++) { int x; scanf("%d", &x); a.push_back(x); l.push_back(i - 1); r.push_back(i + 1); was.push_back(false); } for (int i = 0; i < a.size() - 1; i++) if (s[i] != s[i + 1]) { int x = a[i] - a[i + 1]; if (x > 0) x = -x; q.push(make_pair(x, make_pair(-i, -(i + 1)))); } while (!q.empty()) { pair<int, pair<int, int> > T; T = q.top(); q.pop(); int i = -T.second.first; int j = -T.second.second; if (was[i] || was[j]) continue; was[i] = true; was[j] = true; ans.push_back(make_pair(i + 1, j + 1)); i = lpred(i); j = rpred(j); if (i < 0 || j >= n) continue; if (s[i] == s[j]) continue; int x = a[i] - a[j]; if (x > 0) x = -x; q.push(make_pair(x, make_pair(-i, -j))); } cout << ans.size() << endl; for (int i = 0; i < ans.size(); i++) cout << ans[i].first << " " << ans[i].second << endl; return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; int N, ans, C[200005], L[200005], R[200005]; bool visit[200005], flag; char P[200005]; struct stuff { int A, B; } tmp; struct cmp { bool operator()(stuff a, stuff b) { if (abs(C[a.A] - C[a.B]) != abs(C[b.A] - C[b.B])) return abs(C[a.A] - C[a.B]) < abs(C[b.A] - C[b.B]); if (a.A != b.A) return a.A < b.A; return a.B < b.B; } }; set<stuff, cmp> S; vector<int> A1, A2; int main() { scanf("%d", &N); for (int i = 1; i <= N; ++i) { scanf(" %c", &P[i]); L[i] = i - 1; R[i] = i + 1; } for (int i = 1; i <= N; ++i) scanf("%d", &C[i]); for (int i = 1; i < N; ++i) { if (P[i] != P[i + 1]) { tmp.A = i; tmp.B = i + 1; S.insert(tmp); } } while (!S.empty()) { tmp = *S.begin(); S.erase(tmp); if (!visit[tmp.A] && !visit[tmp.B]) { visit[tmp.A] = visit[tmp.B] = 1; ++ans; A1.push_back(min(tmp.A, tmp.B)); A2.push_back(max(tmp.A, tmp.B)); while (tmp.A >= 1 && visit[tmp.A]) tmp.A = L[tmp.A]; while (tmp.B <= N && visit[tmp.B]) tmp.B = R[tmp.B]; if (tmp.A >= 1) R[tmp.A] = tmp.B; if (tmp.B <= N) L[tmp.B] = tmp.A; if ((tmp.A >= 1 && tmp.B <= N) && P[tmp.A] != P[tmp.B]) S.insert(tmp); } } printf("%d\n", ans); for (int i = 0; i < ans; ++i) printf("%d %d\n", A1[i], A2[i]); }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
from heapq import heappushpop, heapify,heappop,heappush n=int(input()) li = input() a = list(map(int, input().split())) h,seq = [],[] dan = [0]*(n+1) for i in range(n+1)[2:n]: #dan[i]=(Node(li[i-1],i-1,i+1)) dan[i]=[i-1,i+1] #dan[1]=(Node(li[0],None,2)) dan[1] = [None,2] #dan[n]=(Node(li[n-1],n-1,None)) dan[n] = [n-1,None] for i in range(n)[:-1]: if li[i]!=li[i+1]: h.append((abs(a[i+1]-a[i]),(i+1,i+2))) #print(h) #print(dan) notthere=set() #for i in range(n+1)[1:]: # print(dan[i].data) heapify(h) while h: # pop the first in h d = heappop(h) #print(1) # check if it is actually a pair if not(d[1] in notthere): l,r = d[1][0],d[1][1] le = dan[l][0];ri=dan[r][1] L = R = False if le != None: if li[le-1] != li[l-1]: notthere.add((le,l)) #print('aaa') dan[le][1] = ri L =True if ri !=None: if li[ri-1] != li[r-1]: notthere.add((r,ri)) #print('bbb') dan[ri][0] = le R = True if L and R: if li[le-1] != li[ri-1]: heappush(h,(abs(a[le-1]-a[ri-1]),(le,ri))) #print(notthere) seq.append(' '.join([str(l),str(r)])) print(len(seq)) print('\n'.join(seq))
PYTHON3
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
import java.awt.Point; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.PriorityQueue; public class C { static class Que_Elements implements Comparable<Que_Elements> { int diff, id1, id2; public int compareTo(Que_Elements arg0) { if (this.diff==arg0.diff) return this.id1-arg0.id1; return this.diff-arg0.diff; } public Que_Elements(int diff, int id1, int id2) { this.diff = Math.abs(diff); this.id1 = id1; this.id2 = id2; } } public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = Integer.parseInt(br.readLine()); String s = br.readLine(); String[]skils = br.readLine().split(" "); int[]a = new int[n]; for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(skils[i]); } PriorityQueue<Que_Elements> q = new PriorityQueue<Que_Elements>(); int[]left = new int[n], right = new int[n]; for (int i = 0; i < n; i++) { left[i] = i-1; right[i] = i+1; } left[0] = 0; right[n-1] = n-1; for (int i = 0; i < n-1; i++) { if (s.charAt(i) != s.charAt(i+1)) q.add(new Que_Elements(a[i]-a[i+1], i, i+1)); } boolean[]used = new boolean[n]; ArrayList<Point> ans = new ArrayList<Point>(); while (!q.isEmpty()) { Que_Elements firs = q.poll(); if (used[firs.id1] || used[firs.id2]) continue; used[firs.id1] = used[firs.id2] = true; ans.add(new Point(firs.id1, firs.id2)); int l = left[firs.id1], r = right[firs.id2]; right[l] = r; left[r] = l; if (s.charAt(l) != s.charAt(r)) q.add(new Que_Elements(a[l]-a[r], l, r)); } pw.println(ans.size()); for (Point p : ans) { pw.println((p.x+1)+" "+(p.y+1)); } pw.close(); } }
JAVA
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
__author__ = 'Utena' from heapq import heappushpop, heapify,heappop,heappush n=int(input()) danced=[0]*(n+1) gender=[0]+list(input()) skill=[0]+list(map(int,input().split())) next=[0]+[i+1 for i in range(1,n)]+[0] prev=[0]+[i for i in range(n)] ans=[] line=[] total=0 for i in range(1,n): x,y=i,i+1 if gender[x]==gender[y]:continue else: line.append((abs(skill[x]-skill[y]),(x,y))) heapify(line) while len(line)>0: t0,temp=heappop(line) x,y=temp[0],temp[1] if danced[x]+danced[y]==0: ans.append(str(x)+' '+str(y)) total+=1 danced[x]=1 danced[y]=1 if x>1 and y<n: a=prev[x] b=next[y] prev[b]=a next[a]=b if gender[a]!=gender[b]: heappush(line,(abs(skill[a]-skill[b]),(a,b))) print(total) print('\n'.join(ans))
PYTHON3
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; pair<long long, long long> tree[1000009]; long long ar[1000009], pr[1000009], L[1000009], R[1000009], LEF[1000009], RI[1000009]; vector<pair<long long, long long> > vec; void init(long long node, long long beg, long long end) { if (beg == end) { tree[node] = make_pair(R[beg], beg); return; } long long Left = node * 2; long long Right = node * 2 + 1; long long mid = (beg + end) / 2; init(Left, beg, mid); init(Right, mid + 1, end); tree[node] = min(tree[Left], tree[Right]); } pair<long long, long long> query(long long node, long long beg, long long end, long long i, long long j) { if (i > end || j < beg) return make_pair(1LL << 40, 1LL << 40); if (beg >= i && end <= j) return tree[node]; long long Left = node * 2; long long Right = node * 2 + 1; long long mid = (beg + end) / 2; pair<long long, long long> p1 = query(Left, beg, mid, i, j); pair<long long, long long> p2 = query(Right, mid + 1, end, i, j); return min(p1, p2); } void update(long long node, long long beg, long long end, long long i, long long newvalue) { if (i > end || i < beg) return; if (beg >= i && end <= i) { tree[node] = make_pair(newvalue, i); return; } long long Left = node * 2; long long Right = node * 2 + 1; long long mid = (beg + end) / 2; update(Left, beg, mid, i, newvalue); update(Right, mid + 1, end, i, newvalue); tree[node] = min(tree[Left], tree[Right]); } int main() { long long n, i, j, k, l, ans, ind, ind1, ind2, ind3; char ch; pair<long long, long long> NOW; cin >> n; for (i = 1; i <= n; i++) { cin >> ch; if (ch == 'B') ar[i] = 0; else ar[i] = 1; } for (i = 1; i <= n; i++) cin >> pr[i]; for (i = 1; i <= n; i++) { L[i] = 1LL << 40; if (i > 1 && ar[i] != ar[i - 1]) L[i] = abs(pr[i] - pr[i - 1]); R[i] = 1LL << 40; if (i < n && ar[i] != ar[i + 1]) R[i] = abs(pr[i + 1] - pr[i]); LEF[i] = i - 1; RI[i] = i + 1; } init(1, 1, n); while (1) { NOW = query(1, 1, n, 1, n); if (NOW.first >= (1LL << 40)) break; ind = NOW.second; ind1 = RI[ind]; ind2 = LEF[ind]; ind3 = RI[ind1]; RI[ind2] = ind3; LEF[ind3] = ind2; if (ind2 == 0 || ind3 == n + 1) update(1, 1, n, ind2, 1LL << 40); else if (ar[ind2] != ar[ind3]) update(1, 1, n, ind2, abs(pr[ind2] - pr[ind3])); else update(1, 1, n, ind2, 1LL << 40); update(1, 1, n, ind, 1LL << 40); update(1, 1, n, ind1, 1LL << 40); vec.push_back(make_pair(ind, ind1)); } ans = vec.size(); cout << ans << endl; for (i = 1; i <= ans; i++) cout << vec[i - 1].first << " " << vec[i - 1].second << endl; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const int INF = 2147483647; const double PI = 3.141592653589793; const int N = 200005; int n, pl[N], um[N], k1, k2, lewy[N], prawy[N], i; pair<int, pair<int, int> > p; set<pair<int, pair<int, int> > > zbior; vector<pair<int, int> > wek; char t[N]; bool used[N]; int main() { scanf("%d %s", &n, &t); for (i = 0; i < n; i++) scanf("%d", &um[i]); for (i = 0; i < n; i++) { lewy[i] = i - 1; prawy[i] = i + 1; pl[i] = (t[i] == 'B'); used[i] = false; } zbior.clear(); wek.resize(0); for (i = 0; i < n - 1; i++) if (pl[i] + pl[i + 1] == 1) zbior.insert(pair<int, pair<int, int> >(abs(um[i] - um[i + 1]), pair<int, int>(i, i + 1))); while (!zbior.empty()) { p = *zbior.begin(); k1 = p.second.first; k2 = p.second.second; zbior.erase(p); if (!used[k1] && !used[k2]) { wek.push_back(pair<int, int>(k1, k2)); if (lewy[k1] != -1) prawy[lewy[k1]] = prawy[k2]; if (prawy[k2] != n) lewy[prawy[k2]] = lewy[k1]; if (lewy[k1] != -1 && prawy[k2] != n && pl[lewy[k1]] + pl[prawy[k2]] == 1) zbior.insert( pair<int, pair<int, int> >(abs(um[lewy[k1]] - um[prawy[k2]]), pair<int, int>(lewy[k1], prawy[k2]))); used[k1] = true; used[k2] = true; } } printf("%d\n", wek.size()); for (i = 0; i < wek.size(); i++) printf("%d %d\n", wek[i].first + 1, wek[i].second + 1); return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; set<pair<int, pair<int, int> > > all; int val[200005]; char str[200005]; int answer[200005][2], cnt, n; int second[4 * 200005]; void modify(int pos, int val, int id = 1, int l = 0, int r = n) { if (r - l < 2) { second[id] = val; return; } int mid = (l + r) >> 1; if (pos < mid) modify(pos, val, 2 * id, l, mid); else modify(pos, val, 2 * id + 1, mid, r); second[id] = second[2 * id] + second[2 * id + 1]; } int sum(int b, int e, int id = 1, int l = 0, int r = n) { if (b >= r || e <= l) return 0; if (l >= b && r <= e) return second[id]; int mid = (l + r) >> 1; return sum(b, e, 2 * id, l, mid) + sum(b, e, 2 * id + 1, mid, r); } int dan(int pos) { if (pos >= n - 1 || sum(pos + 1, n) == n - 1 - pos) return -1; if (sum(pos + 1, pos + 2) == 0) return pos + 1; int l = pos + 1, r = n - 1; while (r - l > 1) { int mid = (l + r) >> 1; if (sum(pos + 1, mid + 1) == mid - pos) l = mid; else r = mid; } return r; } int bam(int pos) { if (pos <= 0 || sum(0, pos) == pos) return -1; if (sum(pos - 1, pos) == 0) return pos - 1; int l = 0, r = pos - 1; while (r - l > 1) { int mid = (l + r) >> 1; if (sum(mid, pos) == pos - mid) r = mid; else l = mid; } return l; } int used[200005]; int main() { int i; scanf("%d", &n); scanf("%s", str); for (i = 0; i < n; i++) scanf("%d", &val[i]); for (i = 0; i < n - 1; i++) if (str[i] != str[i + 1]) all.insert(make_pair(abs(val[i] - val[i + 1]), make_pair(i, i + 1))); while (all.size() > 0) { pair<int, pair<int, int> > now = *(all.begin()); all.erase(all.begin()); int u = now.second.first, v = now.second.second; if (used[u] || used[v]) continue; answer[cnt][0] = u; answer[cnt++][1] = v; used[u] = used[v] = 1; modify(u, 1); modify(v, 1); int lf = bam(u), rt = dan(v); if (lf == -1 || rt == -1 || str[lf] == str[rt]) continue; all.insert(make_pair(abs(val[lf] - val[rt]), make_pair(lf, rt))); } printf("%d\n", cnt); for (i = 0; i < cnt; i++) printf("%d %d\n", answer[i][0] + 1, answer[i][1] + 1); return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; char seq[200005]; int ar[200005], nxt[200005], prv[200005]; bool vis[200005]; set<pair<int, int> > s; vector<pair<int, int> > ans; int main() { int n, i, x, px, ny; scanf("%d", &n); scanf("%s", seq); for (i = 0; i < n; i++) scanf("%d", &ar[i]); for (i = 0; i + 1 < n; i++) { if ((seq[i] == 'B' && seq[i + 1] == 'G') || (seq[i] == 'G' && seq[i + 1] == 'B')) { s.insert(make_pair(fabs(ar[i] - ar[i + 1]), i)); } nxt[i] = i + 1; prv[i] = i - 1; } nxt[n - 1] = -1; while (s.size()) { x = s.begin()->second; s.erase(s.begin()); ans.push_back(make_pair(x, nxt[x])); px = prv[x]; ny = nxt[nxt[x]]; if (px != -1) { nxt[px] = ny; s.erase(make_pair(fabs(ar[px] - ar[x]), px)); } if (ny != -1) { prv[ny] = px; s.erase(make_pair(fabs(ar[nxt[x]] - ar[ny]), nxt[x])); } if (px == -1 || ny == -1) continue; if ((seq[px] == 'B' && seq[ny] == 'G') || (seq[px] == 'G' && seq[ny] == 'B')) { s.insert(make_pair(fabs(ar[px] - ar[ny]), px)); } } printf("%d\n", ans.size()); for (i = 0; i < ans.size(); i++) printf("%d %d\n", ans[i].first + 1, ans[i].second + 1); return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; struct heap { int va, px, py; } d[201000]; int dtot, qq, n, a[201000], q[201000][2], nex[201000], la[201000]; char s[201000]; bool ex[201000]; bool operator<(heap x, heap y) { return (x.va < y.va || (x.va == y.va && x.px < y.px)); } void insert(int x, int y) { dtot++; d[dtot].va = abs(a[x] - a[y]); d[dtot].px = x; d[dtot].py = y; x = dtot; while (x > 1 && d[x] < d[x / 2]) swap(d[x], d[x / 2]), x = x / 2; } void del() { d[1] = d[dtot]; dtot--; int x = 1; while ((x * 2 <= dtot && d[x * 2] < d[x]) || (x * 2 + 1 <= dtot && d[x * 2 + 1] < d[x])) { if (x * 2 + 1 <= dtot && d[x * 2 + 1] < d[x * 2]) swap(d[x], d[x * 2 + 1]), x = x * 2 + 1; else swap(d[x], d[x * 2]), x = x * 2; } } int main() { cin.sync_with_stdio(false); cout.sync_with_stdio(false); cin >> n; cin >> s; for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) ex[i] = true; for (int i = 1; i < n; i++) { nex[i - 1] = i; la[i] = i - 1; if (s[i] != s[i - 1]) insert(i - 1, i); } la[0] = -1; nex[n - 1] = n; while (dtot) { int x = d[1].px, y = d[1].py; del(); if (ex[x] && ex[y]) { qq++; q[qq][0] = x; q[qq][1] = y; ex[x] = false; ex[y] = false; x = la[x]; y = nex[y]; if (x >= 0) nex[x] = y; if (y < n) la[y] = x; if (x >= 0 && y < n && s[x] != s[y]) insert(x, y); } } cout << qq << endl; for (int i = 1; i <= qq; i++) cout << q[i][0] + 1 << " " << q[i][1] + 1 << endl; return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.TreeSet; public class DancingLesson { class node implements Comparable<node> { int idx, val; node(int i, int v) { idx = i; val = v; } public int compareTo(node oth) { if (idx==oth.idx) return 0; if (val<oth.val) return -1; if (val==oth.val&& idx < oth.idx) return -1; return 1; } } int maxn = 200010, inf = 1 << 28; node pp[] = new node[maxn]; int nxt[] = new int[maxn], pre[] = new int[maxn], sex[] = new int[maxn], arr[] = new int[maxn]; int ans[] = new int[maxn], cnt; TreeSet<node> set = new TreeSet<node>(); void run() throws IOException { int n = nextInt(); in.nextToken(); String s = in.sval; for (int i = 1; i <= n; i++) { arr[i] = nextInt(); if (s.charAt(i - 1) == 'B') sex[i] = 1; nxt[i] = i + 1; pre[i] = i - 1; } sex[n + 1] = sex[n]; nxt[n] = pre[1] = -1; for (int i = 1; i <= n; i++) { int v = Math.abs(arr[i] - arr[i + 1]); if (sex[i] == sex[i + 1]) v = inf; pp[i] = new node(i, v); set.add(pp[i]); } while (!set.isEmpty()) { // for (node i : set) // System.out.print(i.idx + " "); // System.out.println(); node p = set.first(); if (p.val == inf) break; int idx = p.idx; ans[++cnt] = idx; ans[++cnt] = nxt[idx]; set.remove(pp[idx]); set.remove(pp[nxt[idx]]); // System.out.println(idx+" "+nxt[idx]); int left = pre[idx], right = nxt[nxt[idx]]; if (left != -1) { set.remove(pp[left]); nxt[left] = right; if (right == -1 || sex[left] == sex[right]) pp[left].val = inf; else pp[left].val = Math.abs(arr[left] - arr[right]); set.add(pp[left]); } if (right != -1) pre[right] = left; } out.println(cnt / 2); for (int i = 1; i <= cnt; i += 2) out.println(ans[i] + " " + ans[i + 1]); out.close(); } StreamTokenizer in = new StreamTokenizer(new BufferedReader( new InputStreamReader(System.in))); int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); public static void main(String[] args) throws IOException { new DancingLesson().run(); } }
JAVA
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; struct parr { int w, pos1, pos2; }; bool operator<(const parr& a, const parr& b) { return a.w > b.w || (a.w == b.w && a.pos1 >= b.pos1); } int main() { priority_queue<parr> q; int n; int i, j; int num = 0; cin >> n; bool U[n]; int prev[n], next[n]; for (i = 0; i < n; ++i) { U[i] = 0; prev[i] = i - 1; next[i] = i + 1; } prev[0] = -1; next[n - 1] = -1; int A[n]; char B[n]; queue<parr> st; for (i = 0; i < n; ++i) { cin >> B[i]; } for (i = 0; i < n; ++i) { cin >> A[i]; } parr tmp; for (int i = 0; i < n - 1; ++i) { if (B[i] != B[i + 1]) { tmp.w = fabs(A[i] - A[i + 1]); tmp.pos1 = i; tmp.pos2 = i + 1; q.push(tmp); } } while (!q.empty()) { tmp = q.top(); q.pop(); if (!U[tmp.pos1] && !U[tmp.pos2]) { st.push(tmp); U[tmp.pos1] = true; U[tmp.pos2] = true; next[prev[tmp.pos1]] = next[tmp.pos1]; prev[next[tmp.pos1]] = prev[tmp.pos1]; next[prev[tmp.pos2]] = next[tmp.pos2]; prev[next[tmp.pos2]] = prev[tmp.pos2]; i = tmp.pos1 - 1; j = tmp.pos2 + 1; if (prev[tmp.pos1] != -1 && next[tmp.pos2] != -1) { tmp.pos1 = prev[tmp.pos1]; tmp.pos2 = next[tmp.pos2]; tmp.w = fabs(A[tmp.pos1] - A[tmp.pos2]); if (B[tmp.pos1] != B[tmp.pos2]) { q.push(tmp); } } } } cout << st.size() << endl; while (!st.empty()) { cout << min(st.front().pos1, st.front().pos2) + 1 << " " << max(st.front().pos1, st.front().pos2) + 1 << endl; st.pop(); } return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const int N = 220000; set<pair<int, int> > S; int a[N], prv[N], nxt[N]; char s[N]; int main() { int n; scanf("%i%s", &n, s + 1); for (int i = 1; i <= n; i++) scanf("%i", &a[i]); for (int i = 1; i <= n; i++) prv[i] = i - 1, nxt[i] = i + 1; for (int i = 1; i < n; i++) { if (s[i] != s[i + 1]) S.insert(make_pair(abs(a[i + 1] - a[i]), i)); } vector<pair<int, int> > ans; while (!S.empty()) { auto it = S.begin(); int i = it->second, j = nxt[i]; int l = prv[i], r = nxt[j]; if (l > 0 && s[l] != s[i]) S.erase(make_pair(abs(a[l] - a[i]), l)); if (r <= n && s[r] != s[j]) S.erase(make_pair(abs(a[r] - a[j]), j)); if (l > 0 && r <= n && s[l] != s[r]) S.insert(make_pair(abs(a[r] - a[l]), l)); if (l > 0) nxt[l] = r; if (r <= n) prv[r] = l; ans.push_back(make_pair(i, j)); S.erase(it); } cout << ans.size() << endl; for (auto p : ans) printf("%d %d\n", p.first, p.second); return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class ProblemC_K_3_ZKSH_2010_2011 { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE")!=null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException{ if (ONLINE_JUDGE){ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); }else{ in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException{ while(!tok.hasMoreTokens()){ tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException{ return Integer.parseInt(readString()); } long readLong() throws IOException{ return Long.parseLong(readString()); } double readDouble() throws IOException{ return Double.parseDouble(readString()); } public static void main(String[] args){ new ProblemC_K_3_ZKSH_2010_2011().run(); } public void run(){ try{ long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = "+(t2-t1)); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } static class Utils { private Utils() {} public static void mergeSort(int[] a) { mergeSort(a, 0, a.length - 1); } private static void mergeSort(int[] a, int leftIndex, int rightIndex) { final int MAGIC_VALUE = 50; if (leftIndex < rightIndex) { if (rightIndex - leftIndex <= MAGIC_VALUE) { insertionSort(a, leftIndex, rightIndex); } else { int middleIndex = (leftIndex + rightIndex) / 2; mergeSort(a, leftIndex, middleIndex); mergeSort(a, middleIndex + 1, rightIndex); merge(a, leftIndex, middleIndex, rightIndex); } } } private static void merge(int[] a, int leftIndex, int middleIndex, int rightIndex) { int length1 = middleIndex - leftIndex + 1; int length2 = rightIndex - middleIndex; int[] leftArray = new int[length1]; int[] rightArray = new int[length2]; System.arraycopy(a, leftIndex, leftArray, 0, length1); System.arraycopy(a, middleIndex + 1, rightArray, 0, length2); for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) { if (i == length1) { a[k] = rightArray[j++]; } else if (j == length2) { a[k] = leftArray[i++]; } else { a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++]; } } } private static void insertionSort(int[] a, int leftIndex, int rightIndex) { for (int i = leftIndex + 1; i <= rightIndex; i++) { int current = a[i]; int j = i - 1; while (j >= leftIndex && a[j] > current) { a[j + 1] = a[j]; j--; } a[j + 1] = current; } } } class Pair implements Comparable<Pair>{ int d; int i, j; Pair(int d, int i, int j){ this.d = abs(d); this.i = min(i, j); this.j = max(j, j); } @Override public int compareTo(Pair p){ if (d < p.d) return -1; if (d > p.d) return 1; return i - p.i; } } void solve() throws IOException{ int n = readInt(); char[] c = in.readLine().toCharArray(); int[] a = new int[n]; for (int i = 0; i < n; i++){ a[i] = readInt(); } PriorityQueue<Pair> q = new PriorityQueue<ProblemC_K_3_ZKSH_2010_2011.Pair>(); int[] left = new int[n]; int[] right = new int[n]; for (int i = 1; i < n; i++){ if (c[i-1] + c[i] == 'B' + 'G'){ q.add(new Pair(a[i-1] - a[i], i - 1, i)); } left[i] = i - 1; right[i-1] = i; } right[n-1] = n - 1; boolean[] used = new boolean[n]; ArrayList<Point> list = new ArrayList<Point>(); while (q.size() != 0){ Pair p = q.poll(); if (used[p.i] || used[p.j]) continue; used[p.i] = used[p.j] = true; list.add(new Point(p.i + 1, p.j + 1)); int l = left[p.i]; int r = right[p.j]; right[l] = r; left[r] = l; if (c[l] + c[r] == 'B' + 'G'){ q.add(new Pair(a[l] - a[r], l, r)); } } out.println(list.size()); for (int i = 0; i < list.size(); i++){ out.println(list.get(i).x + " " + list.get(i).y); } } static int[][] step8 = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, -1}, {-1, 1}, {1, 1}}; static int[][] stepKnight = {{-2, -1}, {-2, 1}, {-1, -2}, {-1, 2}, {1, -2}, {1, 2}, {2, -1}, {2, 1}}; static long gcd(long a, long b){ if (a == 0) return b; return gcd(b % a, a); } static long lcm(long a, long b){ return a / gcd(a, b)*b; } static long[] gcdPlus(long a, long b){ long[] d = new long[3]; if (a == 0){ d[0] = b; d[1] = 0; d[2] = 1; }else{ d = gcdPlus(b % a, a); long r = d[1]; d[1] = d[2] - b/a*d[1]; d[2] = r; } return d; } static long binpow(long a, int n){ if (n == 0) return 1; if ((n & 1) == 0){ long b = binpow(a, n/2); return b*b; }else return binpow(a, n - 1)*a; } static long binpowmod(long a, int n, long m){ if (m == 1) return 0; if (n == 0) return 1; if ((n & 1) == 0){ long b = binpowmod(a, n/2, m); return (b*b) % m; }else return binpowmod(a, n - 1, m)*a % m; } static long phi(long n){ int[] p = Sieve((int)ceil(sqrt(n)) + 2); long phi = 1; for (int i = 0; i < p.length; i++){ long x = 1; while (n % p[i] == 0){ n /= p[i]; x *= p[i]; } phi *= x - x/p[i]; } if (n != 1) phi *= n - 1; return phi; } static long f(long n, int x, int k){ //οΏ½οΏ½οΏ½-οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½ (οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ 0), οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½ οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½ 0 οΏ½οΏ½ k-1 if (n == 0) return 1; long b = binpow(10, x - 1); long c = n / b; return (c < k? c: k)*binpow(k, x - 1) + (c < k? 1: 0)*f(n % b, x - 1, k); } static long fib(int n){ if (n == 0) return 0; if ((n & 1) == 0){ long f1 = fib(n/2 - 1); long f2 = fib(n/2 + 1); return f2*f2 - f1*f1; }else{ long f1 = fib(n/2); long f2 = fib(n/2 + 1); return f1*f1 + f2*f2; } } static BigInteger BigFib(int n){ if (n == 0) return BigInteger.ZERO; if ((n & 1) == 0){ BigInteger f1 = BigFib(n/2 - 1); f1 = f1.multiply(f1); BigInteger f2 = BigFib(n/2 + 1); f2 = f2.multiply(f2); return f2.subtract(f1); }else{ BigInteger f1 = BigFib(n/2); f1 = f1.multiply(f1); BigInteger f2 = BigFib(n/2 + 1); f2 = f2.multiply(f2); return f2.add(f1); } } static public class PointD{ double x, y; public PointD(double x, double y){ this.x = x; this.y = y; } } static double d(Point p1, Point p2){ return sqrt(d2(p1, p2)); } static public double d(PointD p1, PointD p2){ return sqrt(d2(p1, p2)); } static double d2(Point p1, Point p2){ return (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y); } static public double d2(PointD p1, PointD p2){ return (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y); } static boolean IsProbablyPrime(long n){ if (n == 1) return false; if ((n & 1) == 0) return false; for (int j = 3; j < sqrt(n) + 1; j += 2){ if (n % j == 0) return false; } return true; } static int[] Sieve(int n){ boolean[] b = new boolean[n+1]; Arrays.fill(b, true); b[0] = false; b[1] = false; long nLong = n; int j=0; for (int i = 1; i <= n; i++) { if (b[i]){ j++; if (((long)i)*i <= nLong) { for (int k = i*i; k <= n; k += i) { b[k] = false; } } } } int[] p = new int[j]; Arrays.fill(p, 0); j=0; for (int i = 2; i <= n; i++) { if (b[i]){ p[j]=i; j++; } } return p; } static int[][] Palindromes(String s){ char[] c = s.toCharArray(); int n = c.length; int[][] d = new int[2][n]; int l = 0, r = -1; for (int i = 0; i < n; i++){ int j = (i > r? 0: min(d[0][l+r-i+1], r-i+1)) + 1; for (; i - j >= 0 && i + j - 1< n && c[i-j] == c[i+j-1]; j++); d[0][i] = --j; if (i + d[0][i] - 1 > r){ r = i + d[0][i] - 1; l = i - d[0][i]; } } l = 0; r = -1; for (int i = 0; i < n; i++){ int j = (i > r? 0: min(d[1][l+r-i], r-i)) + 1; for (; i - j >= 0 && i + j < n && c[i-j] == c[i+j]; j++); d[1][i] = --j; if (i + d[1][i] > r){ r = i + d[1][i]; l = i - d[1][i]; } } return d; } static public class Permutation { int[] a; int n; public Permutation(int n){ this.n=n; a=new int[n]; for (int i=0; i<n; i++){ a[i]=i; } } public boolean nextPermutation(){ //οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½ do{}while(nextPermutation(a)); int i=n-1; for (i=n-2; i>=0; i--){ if (a[i]<a[i+1]){ break; } } if (i==-1){ return false; } int jMin=i+1; for (int j=n-1; j>i; j--){ if (a[i]<a[j]&&a[j]<a[jMin]){ jMin=j; } } swap(i, jMin); for (int j=1; j<=(n-i)/2; j++){ swap(i+j, n-j); } return true; } public int get(int i){ return a[i]; } void swap(int i, int j){ int r=a[i]; a[i]=a[j]; a[j]=r; } } static public class Fraction implements Comparable<Fraction>, Cloneable{ public final Fraction FRACTION_ZERO = new Fraction(); public final Fraction FRACTION_ONE = new Fraction(1); public long numerator = 0; public long denominator = 1; public Fraction(){ numerator = 0; denominator = 1; } public Fraction(long numerator){ this.numerator = numerator; denominator = 1; } public Fraction(long numerator, long denominator){ this.numerator = numerator; this.denominator = denominator; Cancellation(); } public Fraction(double numerator, double denominator, int accuracy){ this.numerator = (long)(numerator*pow(10,accuracy)); this.denominator = (long)(denominator*pow(10,accuracy)); Cancellation(); } public Fraction(String s){ if (s.charAt(0) == '-'){ denominator = -1; s = s.substring(1); } if (s.indexOf("/") != -1){ denominator *= Integer.parseInt(s.substring(s.indexOf("/") + 1)); } if (s.indexOf(" ") != -1){ numerator = Integer.parseInt(s.substring(0, s.indexOf(" "))) * abs(denominator) + Integer.parseInt(s.substring(s.indexOf(" ") + 1, s.indexOf("/"))); }else{ if (s.indexOf("/") != -1){ numerator = Integer.parseInt(s.substring(0, s.indexOf("/"))); }else{ numerator = Integer.parseInt(s)*abs(denominator); } } this.Cancellation(); } void Cancellation(){ long g = gcd(abs(numerator), abs(denominator)); numerator /= g; denominator /= g; if (denominator < 0){ numerator *= -1; denominator *= -1; } } public String toString(){ String s = ""; if (numerator == 0){ return "0"; } if (numerator < 0){ s += "-"; } if (abs(numerator) >= denominator){ s += Long.toString(abs(numerator) / denominator) + " "; } if (abs(numerator) % denominator != 0){ s += Long.toString(abs(numerator) % denominator); }else{ s = s.substring(0, s.length()-1); } if (denominator != 1){ s += "/" + Long.toString(denominator); } return s; } public Fraction add(Fraction f){ Fraction fResult = new Fraction(); fResult.denominator = lcm(denominator, f.denominator); fResult.numerator = numerator * fResult.denominator / denominator + f.numerator * fResult.denominator / f.denominator; fResult.Cancellation(); return fResult; } public Fraction subtract(Fraction f){ Fraction fResult = new Fraction(); fResult.denominator = lcm(denominator, f.denominator); fResult.numerator = numerator * fResult.denominator / denominator - f.numerator * fResult.denominator / f.denominator; fResult.Cancellation(); return fResult; } public Fraction multiply(Fraction f){ Fraction fResult = new Fraction(); fResult.numerator = numerator * f.numerator; fResult.denominator = denominator * f.denominator; fResult.Cancellation(); return fResult; } public Fraction divide(Fraction f){ Fraction fResult = new Fraction(); fResult.numerator = numerator * f.denominator; fResult.denominator = denominator * f.numerator; fResult.Cancellation(); return fResult; } @Override public int compareTo(Fraction f){ long g = gcd(denominator, f.denominator); long res = numerator * (f.denominator / g) - f.numerator * (denominator / g); if (res < 0){ return -1; } if (res > 0){ return 1; } return 0; } public Fraction clone(){ Fraction fResult = new Fraction(numerator, denominator); return fResult; } public Fraction floor(){ Fraction fResult = this.clone(); fResult.numerator = (fResult.numerator / fResult.denominator) * fResult.denominator; return fResult; } public Fraction ceil(){ Fraction fResult = this.clone(); fResult.numerator = (fResult.numerator/fResult.denominator + 1) * fResult.denominator; return fResult; } public Fraction binpow(int n){ if (n==0) return FRACTION_ONE; if ((n&1)==0){ Fraction f=this.binpow(n/2); return f.multiply(f); }else return binpow(n-1).multiply(this); } } static public class FenwickTree_1{ //One-dimensional array int n; long[] t; public FenwickTree_1(int n){ this.n = n; t = new long[n]; } public long sum(int xl, int xr){ return sum(xr) - sum(xl); } public long sum(int x){ long result = 0; for (int i = x; i >= 0; i = (i & (i + 1)) - 1){ result += t[i]; } return result; } public void update(int x, long delta){ for (int i = x; i < n; i = (i | (i + 1))){ t[i] += delta; } } } static public class FenwickTree_2{ //Two-dimensional array int n, m; long[][] t; public FenwickTree_2(int n, int m){ this.n = n; this.m = m; t = new long[n][m]; } public long sum(int xl, int yl, int xr, int yr){ return sum(xr, yr) - sum(xl - 1, yr) - sum(xr, yl - 1) + sum(xl - 1, yl - 1); } public long sum(int x, int y){ long result = 0; for (int i = x; i >= 0; i = (i & (i + 1)) - 1){ for (int j = y; j >= 0; j = (j & (j + 1)) - 1){ result+=t[i][j]; } } return result; } public void update(int x, int y, long delta){ for (int i = x; i < n; i = (i | (i + 1))){ for (int j = y; j < m; j = (j | (j + 1))){ t[i][j] += delta; } } } } static public class FenwickTree_3{ //Three-dimensional array int n, m, l; long[][][] t; public FenwickTree_3(int n, int m, int l){ this.n = n; this.m = m; this.l = l; t = new long[n][m][l]; } public long sum(int xl, int yl, int zl, int xr, int yr, int zr){ return sum(xr, yr, zr) - sum(xl - 1, yr, zr) + sum(xl - 1, yr, zl - 1) - sum(xr, yr, zl - 1) - sum(xr, yl - 1, zr) + sum(xl - 1, yl - 1, zr) - sum(xl - 1, yl - 1, zl - 1) + sum(xr, yl - 1, zl - 1); } public long sum(int x, int y, int z){ long result = 0; for (int i = x; i >= 0; i = (i & (i + 1)) - 1){ for (int j = y; j >= 0; j = (j & (j + 1)) - 1){ for (int k = z; k >= 0; k = (k & (k + 1)) - 1){ result += t[i][j][k]; } } } return result; } public void update(int x, int y, int z, long delta){ for (int i = x; i < n; i = (i | (i + 1))){ for (int j = y; j < n; j = (j | (j + 1))){ for (int k = z; k < n; k = (k | (k + 1))){ t[i][j][k] += delta; } } } } } }
JAVA
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
from heapq import heappush,heappop,heapify n=int(input()) symbols=input() skl=list(map(int,input().split())) LMap=[i-1 for i in range(n+1)] RMap=[i+1 for i in range(n+1)] LMap[1],RMap[n]=1,n h=[] res=[] cnt=0 B=symbols.count("B") N=min(n-B,B) ind=[False]*(n+1) for i in range(n-1) : if symbols[i]!=symbols[i+1] : h.append((abs(skl[i]-skl[i+1]),i+1,i+2)) heapify(h) i=0 while cnt<N : d,L,R=heappop(h) if ind[L] or ind[R] : continue cnt+=1 ind[L],ind[R]=True,True res.append(str(L)+" "+str(R)) L,R=LMap[L],RMap[R] if L<1 or R>n : continue RMap[L],LMap[R]=R,L if symbols[L-1]!=symbols[R-1] : heappush(h,(abs(skl[L-1]-skl[R-1]),L,R)) assert cnt==N print(cnt) for i in res : print(i)
PYTHON3
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5; const int INF = 0x3f3f3f3f; char s[N]; int n, a[N], l[N], r[N], ans[N][2], vis[N]; struct node { int u, v, w; } tp; bool operator<(node p, node q) { if (p.w == q.w) return p.u > q.u; return p.w > q.w; } int ok(int a, int b) { return 1 <= a && a < b && b <= n; } int main() { while (scanf("%d%s", &n, s + 1) != EOF) { memset(vis, 0, sizeof vis); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); for (int i = 1; i <= n; i++) { l[i] = i - 1; r[i] = i + 1; } priority_queue<node> q; for (int i = 2; i <= n; i++) if (s[i] != s[i - 1]) { tp.u = i - 1, tp.v = i; tp.w = abs(a[i] - a[i - 1]); q.push(tp); } int ansn = 0; while (!q.empty()) { node tp = q.top(); q.pop(); int x = tp.u, y = tp.v; if (!vis[x] && !vis[y]) { vis[x] = vis[y] = 1; ans[ansn][0] = x, ans[ansn++][1] = y; x = l[x], y = r[y]; if (ok(x, y) && s[x] != s[y]) { tp.u = x, tp.v = y, tp.w = abs(a[x] - a[y]); q.push(tp); } r[x] = y, l[y] = x; } } printf("%d\n", ansn); for (int i = 0; i < ansn; i++) printf("%d %d\n", ans[i][0], ans[i][1]); } return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const int maxN = 200 * 1000 + 5; const int mod = 1000 * 1000 * 1000 + 7; string s; set<int> se; set<pair<int, int> > an; int a[maxN]; int main() { ios::sync_with_stdio(0); cin.tie(0); int n; cin >> n; cin >> s; for (int i = 0; i < n; i++) cin >> a[i], se.insert(i); for (int i = 1; i < n; i++) if (s[i] != s[i - 1]) an.insert(make_pair(abs(a[i] - a[i - 1]), i - 1)); vector<pair<int, int> > ans; while (an.size()) { auto tmp = *an.begin(); int x = *se.upper_bound(tmp.second), y = tmp.second; ans.push_back(make_pair(tmp.second, x)); an.erase(tmp); auto itl = se.find(tmp.second); auto itr = se.find(x); int lx = -1, rx = -1; if (itl != se.begin()) { itl--; lx = *itl; } itr++; if (itr != se.end()) rx = *itr; if (lx > -1 && s[lx] != s[y]) an.erase(make_pair(abs(a[lx] - a[y]), lx)); if (rx > -1 && s[rx] != s[x]) an.erase(make_pair(abs(a[rx] - a[x]), x)); if (rx > -1 && lx > -1 && s[lx] != s[rx]) an.insert(make_pair(abs(a[rx] - a[lx]), lx)); se.erase(x); se.erase(y); } cout << ans.size() << endl; for (auto u : ans) cout << u.first + 1 << ' ' << u.second + 1 << endl; return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const int maxn = 300005; int L[maxn], R[maxn], skill[maxn]; char s[maxn]; int n; bool vis[maxn]; struct node { int u; int v; int c; }; bool operator<(const node a, const node b) { if (a.c ^ b.c) return a.c > b.c; else return a.u > b.u; } priority_queue<node> q; int main() { while (cin >> n) { while (!q.empty()) q.pop(); cin >> s + 1; node z; int num = 0; for (int i = 1; i <= n; i++) { L[i] = i - 1; R[i] = i + 1; if (s[i] == 'B') { num += 1; } } num = min(num, n - num); for (int i = 1; i <= n; i++) cin >> skill[i]; for (int i = 1; i < n; i++) { if (s[i] != s[i + 1]) { z.u = i; z.v = i + 1; z.c = abs(skill[i] - skill[i + 1]); q.push(z); } } printf("%d\n", num); memset(vis, 0, sizeof(vis)); while (num--) { while (!q.empty()) { z = q.top(); q.pop(); if (!vis[z.u] && !vis[z.v]) { printf("%d %d\n", z.u, z.v); vis[z.u] = 1; vis[z.v] = 1; break; } } int b = L[z.u]; int t = R[z.v]; R[b] = t; L[t] = b; z.u = b; z.v = t; z.c = abs(skill[b] - skill[t]); if (b > 0 && t <= n && s[b] != s[t]) q.push(z); } } return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const int maxn = 200005; int SZ[maxn]; int K[maxn]; int LC[maxn]; int RC[maxn]; class SizeBalanceTree { public: void clear() { sz = 0; LC[0] = RC[0] = 0; SZ[0] = 0; root = 0; } int Size() { return SZ[root]; } bool empty() { return root == 0; } void Build(int s, int e) { Build(root, s, e); } bool Find(int key) { return Find(root, key); } void Insert(int key) { Insert(root, key); } void Delete(int key) { Delete(root, key); } int DeleteSelect(int k) { return DeleteSelect(root, k); } void DeleteSmall(int key) { DeleteSmall(root, key); } int Rank(int key) { return Rank(root, key); } int Select(int k) { return Select(root, k); } int pred(int key) { return pred(root, key); } int succ(int key) { return succ(root, key); } int getMin() { int temp = root; while (LC[temp]) temp = LC[temp]; return K[temp]; } int getMax() { int temp = root; while (RC[temp]) temp = RC[temp]; return K[temp]; } int DeleteMax() { int temp = root; if (RC[root] == 0) { root = LC[root]; return K[temp]; } while (RC[RC[temp]]) { SZ[temp]--; temp = RC[temp]; } SZ[temp]--; int ret = K[RC[temp]]; RC[temp] = LC[RC[temp]]; return ret; } int DeleteMin() { int temp = root; if (LC[root] == 0) { root = RC[root]; return K[temp]; } while (LC[LC[temp]]) { SZ[temp]--; temp = LC[temp]; } SZ[temp]--; int ret = K[LC[temp]]; LC[temp] = RC[LC[temp]]; return ret; } public: int root, sz; void Build(int &root, int s, int e) { if (s > e) return; int mid = (s + e) / 2; root = ++sz; K[root] = mid; LC[root] = 0; RC[root] = 0; SZ[root] = e - s + 1; if (s == e) return; Build(LC[root], s, mid - 1); Build(RC[root], mid + 1, e); } bool Find(int &root, int key) { if (root == 0) { return false; } else if (key < K[root]) { return Find(LC[root], key); } else { return (K[root] == key || Find(RC[root], key)); } } void Insert(int &root, int key) { if (root == 0) { root = ++sz; LC[root] = RC[root] = 0; SZ[root] = 1; K[root] = key; return; } SZ[root]++; if (key < K[root]) { Insert(LC[root], key); } else { Insert(RC[root], key); } maintain(root, !(key < K[root])); } int Delete(int &root, int key) { SZ[root]--; if ((K[root] == key) || (key < K[root] && LC[root] == 0) || (K[root] < key && RC[root] == 0)) { int ret = K[root]; if (LC[root] == 0 || RC[root] == 0) { root = LC[root] + RC[root]; } else { K[root] = Delete(LC[root], K[root] + 1); } return ret; } else { if (key < K[root]) { return Delete(LC[root], key); } else { return Delete(RC[root], key); } } } void DeleteSmall(int &root, int key) { if (root == 0) return; if (K[root] < key) { root = RC[root]; DeleteSmall(root, key); } else { DeleteSmall(LC[root], key); SZ[root] = 1 + SZ[LC[root]] + SZ[RC[root]]; } } int Rank(int &root, int key) { if (root == 0) return 0; if (K[root] == key) { return Rank(LC[root], key) + 1; } else if (key < K[root]) { return Rank(LC[root], key); } else { return SZ[LC[root]] + 1 + Rank(RC[root], key); } } int Select(int &root, int k) { if (SZ[LC[root]] + 1 == k) { return K[root]; } else if (k > SZ[LC[root]]) { return Select(RC[root], k - 1 - SZ[LC[root]]); } else { return Select(LC[root], k); } } int DeleteSelect(int &root, int k) { SZ[root]--; if (SZ[LC[root]] + 1 == k) { int ret = K[root]; if (LC[root] == 0 || RC[root] == 0) { root = LC[root] + RC[root]; } else { K[root] = Delete(LC[root], K[root] + 1); } return ret; } else if (k > SZ[LC[root]]) { return DeleteSelect(RC[root], k - 1 - SZ[LC[root]]); } else { return DeleteSelect(LC[root], k); } } int pred(int &root, int key) { if (root == 0) { return key; } else if (key > K[root]) { int ret = pred(RC[root], key); if (ret == key) return K[root]; return ret; } else { return pred(LC[root], key); } } int succ(int &root, int key) { if (root == 0) { return key; } else if (K[root] > key) { int ret = succ(LC[root], key); if (ret == key) return K[root]; return ret; } else { return succ(RC[root], key); } } void LeftRotate(int &root) { int temp = RC[root]; RC[root] = LC[temp]; LC[temp] = root; SZ[temp] = SZ[root]; SZ[root] = 1 + SZ[LC[root]] + SZ[RC[root]]; root = temp; } void RightRotate(int &root) { int temp = LC[root]; LC[root] = RC[temp]; RC[temp] = root; SZ[temp] = SZ[root]; SZ[root] = 1 + SZ[LC[root]] + SZ[RC[root]]; root = temp; } void maintain(int &root, bool flag) { if (root == 0) return; if (!flag) { if (SZ[LC[LC[root]]] > SZ[RC[root]]) { RightRotate(root); } else if (SZ[RC[LC[root]]] > SZ[RC[root]]) { LeftRotate(LC[root]); RightRotate(root); } else { return; } } else { if (SZ[RC[RC[root]]] > SZ[LC[root]]) { LeftRotate(root); } else if (SZ[LC[RC[root]]] > SZ[LC[root]]) { RightRotate(RC[root]); LeftRotate(root); } else { return; } } maintain(LC[root], false); maintain(RC[root], true); maintain(root, false); maintain(root, true); } }; int n; struct ab { int a; int b; int val; bool operator<(const ab &A) const { if (A.val < val) return 1; if (A.val == val && A.a < a) return 1; if (A.val == val && A.a == a && A.b < b) return 1; return 0; } } temp, now; struct abc { int a; int b; } ans[maxn]; int an; bool vis[200005]; int data[200005]; char str[200005]; int main() { int i, len; while (scanf("%d", &n) != EOF) { memset(vis, 0, sizeof(vis)); SizeBalanceTree sbt; sbt.clear(); priority_queue<ab> que; scanf("%s", &str); for (i = 0; i < n; i++) { scanf("%d", &data[i]); sbt.Insert(i); } an = 0; for (i = 0; i < n - 1; i++) { if (str[i] != str[i + 1]) { temp.a = i; temp.b = i + 1; temp.val = abs(data[i] - data[i + 1]); que.push(temp); } } while (!que.empty()) { now = que.top(); que.pop(); if (vis[now.a] == 0 && vis[now.b] == 0) { ans[an].a = now.a; ans[an].b = now.b; an++; vis[now.a] = 1; vis[now.b] = 1; int zuo = sbt.pred(now.a); int you = sbt.succ(now.b); if (zuo != now.a && you != now.b) { if (str[zuo] != str[you]) { temp.a = zuo; temp.b = you; temp.val = abs(data[zuo] - data[you]); que.push(temp); } } sbt.Delete(now.a); sbt.Delete(now.b); } } printf("%d\n", an); for (i = 0; i < an; i++) { printf("%d %d\n", ans[i].a + 1, ans[i].b + 1); } } }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; int n; string s; int a[200007]; int prv[200007]; int nxt[200007]; int used[200007]; struct tuhla { int diff; int l, r; }; bool operator<(struct tuhla p1, struct tuhla p2) { if (p1.diff != p2.diff) { return (p1.diff > p2.diff); } return (p1.l > p2.l); } priority_queue<struct tuhla> q; void input() { cin >> n; cin >> s; int i; s = '#' + s; for (i = 1; i <= n; i++) { cin >> a[i]; prv[i] = i - 1; nxt[i] = i + 1; } struct tuhla u; for (i = 1; i < n; i++) { if (s[i] != s[i + 1]) { u.l = i; u.r = i + 1; u.diff = abs(a[i] - a[i + 1]); q.push(u); } } } void solve() { int i; struct tuhla u, e; vector<pair<int, int> > v; while (q.empty() == false) { u = q.top(); q.pop(); if (used[u.l] == 1 || used[u.r] == 1) { continue; } used[u.l] = used[u.r] = 1; v.push_back(make_pair(u.l, u.r)); nxt[prv[u.l]] = nxt[u.r]; prv[nxt[u.r]] = prv[u.l]; int id = prv[u.l]; if (id != 0 && nxt[id] <= n) { if (s[id] != s[nxt[id]]) { e.l = id; e.r = nxt[id]; e.diff = abs(a[e.l] - a[e.r]); q.push(e); } } } int sz = v.size(); cout << sz << "\n"; for (i = 0; i < sz; i++) { cout << v[i].first << " " << v[i].second << "\n"; } } int main() { ios::sync_with_stdio(false); cin.tie(NULL); input(); solve(); return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; inline void read() {} template <typename F, typename S> ostream &operator<<(ostream &os, const pair<F, S> &p) { return os << "(" << p.first << ", " << p.second << ")"; } template <typename T> ostream &operator<<(ostream &os, const vector<T> &v) { os << "{"; typename vector<T>::const_iterator it; for (it = v.begin(); it != v.end(); it++) { if (it != v.begin()) os << ", "; os << *it; } return os << "}"; } template <typename T> ostream &operator<<(ostream &os, const set<T> &v) { os << "["; typename set<T>::const_iterator it; for (it = v.begin(); it != v.end(); it++) { if (it != v.begin()) os << ", "; os << *it; } return os << "]"; } template <typename F, typename S> ostream &operator<<(ostream &os, const map<F, S> &v) { os << "["; typename map<F, S>::const_iterator it; for (it = v.begin(); it != v.end(); it++) { if (it != v.begin()) os << ", "; os << it->first << " = " << it->second; } return os << "]"; } long long arr[200007]; struct DATA { long long idx1, idx2, val; bool operator<(const DATA &prev) const { if (val != prev.val) return val > prev.val; return idx1 > prev.idx1; } }; priority_queue<DATA> PQ; DATA temp; set<long long> available_dancers; set<long long>::iterator it; long long n; string str; void InsertPair(int id1, int id2) { if (id1 == id2) return; bool flag = 1; it = available_dancers.find(id1); if (it == available_dancers.end()) flag = 0; it = available_dancers.find(id2); if (it == available_dancers.end()) flag = 0; if (str[id1] == str[id2]) { flag = 0; } if (!flag) return; temp.idx1 = min(id1, id2); temp.idx2 = max(id1, id2); temp.val = abs(arr[id1] - arr[id2]); PQ.push(temp); return; } void call(int id1) { long long x, y; it = available_dancers.lower_bound(id1 + 1); if (it == available_dancers.end()) y = -1; else y = *it; if (it != available_dancers.begin() && y != -1) { it--; x = *it; } else { x = -1; } InsertPair(x, y); } int main(void) { ios_base::sync_with_stdio(0); cin.tie(0); read(); cin >> n >> str; for (__typeof(n) i = 0; i < (n); i++) { cin >> arr[i]; } for (__typeof(n - 1) i = 0; i < (n - 1); i++) { if (str[i] != str[i + 1]) { temp.idx1 = i; temp.idx2 = i + 1; temp.val = abs(arr[i] - arr[i + 1]); PQ.push(temp); } } for (__typeof(n) i = 0; i < (n); i++) { available_dancers.insert(i); } vector<long long> res1, res2; while (!PQ.empty()) { bool f = 1; temp = PQ.top(); PQ.pop(); long long id1 = temp.idx1; long long id2 = temp.idx2; long long val = temp.val; it = available_dancers.find(id1); if (it == available_dancers.end()) f = 0; it = available_dancers.find(id2); if (it == available_dancers.end()) f = 0; if (f) { res1.push_back(id1 + 1); res2.push_back(id2 + 1); available_dancers.erase(id1); available_dancers.erase(id2); call(id1); call(id2); } } cout << ((int)res1.size()) << "\n"; for (__typeof(((int)res1.size())) i = 0; i < (((int)res1.size())); i++) { cout << res1[i] << " " << res2[i] << "\n"; } }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; int a[200010]; char BG[200010]; int main() { memset(a, 0, sizeof(a)); priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, greater<pair<int, pair<int, int>>>> pq; set<int> num; int n = 0; scanf("%d", &n); scanf("%s", BG + 1); for (int i = 1; i <= n; ++i) { scanf("%d", &a[i]); num.insert(i); } for (int i = 1; i + 1 <= n; ++i) { if (BG[i] != BG[i + 1]) { int tmp = abs(a[i] - a[i + 1]); pq.push(make_pair(tmp, make_pair(i, i + 1))); } } vector<pair<int, int>> res; while (!pq.empty()) { auto cur = pq.top(); pq.pop(); int l = cur.second.first, r = cur.second.second; if (!num.count(l) || !num.count(r)) { continue; } res.push_back(make_pair(l, r)); auto le = num.find(l); if (le != num.begin()) { --le; auto ri = num.find(r); ++ri; if (ri != num.end() && BG[*le] != BG[*ri]) { pq.push(make_pair(abs(a[*le] - a[*ri]), make_pair(*le, *ri))); } } num.erase(l); num.erase(r); } printf("%d\n", (int)res.size()); for (int i = 0; i < res.size(); ++i) { printf("%d %d\n", res[i].first, res[i].second); } return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
import heapq n=int(input()) g=input() a=[int(i) for i in input().split()] h=[] heapq.heapify(h) prev=[i-1 for i in range(0,n)] next=[i+1 for i in range(0,n)] d=[0]*n; r1=[] r2=[] r=[] for i in range(0,n-1): if(g[i]!=g[i+1]): heapq.heappush(h,(abs(a[i]-a[i+1]),i,i+1)) while h : aa,ii,jj=heapq.heappop(h) if(d[ii]==0) and (d[jj]==0): r1.append(ii+1) r2.append(jj+1) d[ii]=1; d[jj]=1; pp=prev[ii]; nn=next[jj]; if(pp>=0) and (nn<n): next[pp]=nn; prev[nn]=pp; if g[nn]!=g[pp]: heapq.heappush(h,(abs(a[nn]-a[pp]),pp,nn)) print(len(r1)); for i in range(len(r1)): r.append(str(r1[i])+' '+str(r2[i])); print(*r,sep='\n');
PYTHON3
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; struct data { int x, y, d; data(int _x, int _y, int _d) { x = _x, y = _y, d = _d; } bool operator<(const data &b) const { if (d == b.d) { if (x == b.x) return y > b.y; return x > b.x; } return d > b.d; } }; string inp; int n, a[200010], v[200010], Left[200010], Right[200010]; priority_queue<data> q; int main() { ios_base::sync_with_stdio(0); memset((Left), (-1), sizeof(Left)); ; memset((Right), (-1), sizeof(Right)); ; cin >> n >> inp; for (__typeof(n) i = 0; i < (n); i++) cin >> a[i]; for (__typeof(n) i = 0; i < (n); i++) { if (i) Left[i] = i - 1; if (i + 1 < n) Right[i] = i + 1; if (!i) continue; if (inp[i] != inp[i - 1]) q.push(data(i - 1, i, abs(a[i] - a[i - 1]))); } vector<pair<int, int> > ans; while (!q.empty()) { data top = q.top(); q.pop(); if (v[top.x] || v[top.y]) continue; v[top.x] = v[top.y] = true; ans.push_back(make_pair(top.x, top.y)); Right[Left[top.x]] = Right[top.y]; Left[Right[top.y]] = Left[top.x]; if (Left[top.x] > -1 && Right[top.y] > -1 && inp[Left[top.x]] != inp[Right[top.y]]) q.push(data(Left[top.x], Right[top.y], abs(a[Left[top.x]] - a[Right[top.y]]))); } cout << ((int)ans.size()) << endl; for (__typeof(((int)ans.size())) i = 0; i < (((int)ans.size())); i++) cout << ans[i].first + 1 << " " << ans[i].second + 1 << endl; return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const int Inf = 1000000000; const int Maxn = 200005; const int Maxm = 1048576; int n; char typ[Maxn]; int a[Maxn]; int L[Maxm], R[Maxm], I[Maxm]; int lef[Maxm], rig[Maxm]; vector<pair<int, int> > res; int Best(int v) { return min(min(L[v], R[v]), I[v]); } void Union(int v) { L[v] = Best(2 * v); R[v] = Best(2 * v + 1); int l = rig[2 * v], r = lef[2 * v + 1]; I[v] = l != -1 && r != -1 && typ[l] != typ[r] ? abs(a[l] - a[r]) : Inf; lef[v] = lef[2 * v] != -1 ? lef[2 * v] : lef[2 * v + 1]; rig[v] = rig[2 * v + 1] != -1 ? rig[2 * v + 1] : rig[2 * v]; } void Create(int v, int l, int r) { if (l == r) { L[v] = R[v] = I[v] = Inf; lef[v] = rig[v] = l; } else { int m = l + r >> 1; Create(2 * v, l, m); Create(2 * v + 1, m + 1, r); Union(v); } } void Find(int v, int l, int r, int &a, int &b) { int m = l + r >> 1; if (L[v] <= I[v] && L[v] <= R[v]) Find(2 * v, l, m, a, b); else if (I[v] <= R[v]) { a = rig[2 * v]; b = lef[2 * v + 1]; } else Find(2 * v + 1, m + 1, r, a, b); } void Erase(int v, int l, int r, int x) { if (l == r) { L[v] = R[v] = I[v] = Inf; lef[v] = rig[v] = -1; } else { int m = l + r >> 1; if (x <= m) Erase(2 * v, l, m, x); else Erase(2 * v + 1, m + 1, r, x); Union(v); } } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf(" %c", &typ[i]); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); Create(1, 1, n); while (Best(1) != Inf) { int a, b; Find(1, 1, n, a, b); res.push_back(pair<int, int>(a, b)); Erase(1, 1, n, a); Erase(1, 1, n, b); } printf("%d\n", res.size()); for (int i = 0; i < res.size(); i++) printf("%d %d\n", res[i].first, res[i].second); return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; string order; cin >> order; vector<int> a(n); for (int i = (0); i < ((n)); ++i) cin >> a[i]; set<pair<int, pair<int, int> > > pairs; map<pair<int, int>, int> pairDiff; for (int i = (0); i < ((n - 1)); ++i) if (order[i] != order[i + 1]) { pairs.insert(make_pair(abs(a[i] - a[i + 1]), make_pair(i, i + 1))); pairDiff[make_pair(i, i + 1)] = abs(a[i] - a[i + 1]); } set<int> people; for (int i = (0); i < ((n)); ++i) people.insert(i); vector<pair<int, int> > res; while (!pairs.empty()) { pair<int, pair<int, int> > cur = *pairs.begin(); pairs.erase(pairs.begin()); res.push_back(cur.second); int i = cur.second.first, j = cur.second.second; int p1 = -1, p2 = -1; { set<int>::const_iterator it = people.find(i); if (it != people.begin()) { --it; p1 = *it; } } { set<int>::const_iterator it = people.upper_bound(j); if (it != people.end()) { p2 = *it; } } people.erase(i); people.erase(j); if (p1 != -1 && pairDiff.count(make_pair(p1, i)) != 0) { pairs.erase(make_pair(pairDiff[make_pair(p1, i)], make_pair(p1, i))); } if (p2 != -1 && pairDiff.count(make_pair(j, p2)) != 0) { pairs.erase(make_pair(pairDiff[make_pair(j, p2)], make_pair(j, p2))); } if (p1 != -1 && p2 != -1 && order[p1] != order[p2]) { pairs.insert(make_pair(abs(a[p1] - a[p2]), make_pair(p1, p2))); pairDiff[make_pair(p1, p2)] = abs(a[p1] - a[p2]); } } cout << (int)res.size() << "\n"; for (int i = (0); i < (((int)res.size())); ++i) { cout << res[i].first + 1 << " " << res[i].second + 1 << "\n"; } return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; char s[200011]; int a[200011]; int ans[100011][2]; int ll[200011], rr[200011]; int vis[200011]; int cnt; struct node { int l, r; int x; friend bool operator<(node a, node b) { if (a.x == b.x) return a.l > b.l; return a.x > b.x; } }; priority_queue<node> q; int main() { int n; while (scanf("%d", &n) != EOF) { memset(vis, 0, sizeof(vis)); for (int i = 0; i <= n; i++) { ll[i] = i - 1; rr[i] = i + 1; } cnt = 0; scanf("%s", s); for (int i = 0; i < n; i++) scanf("%d", &a[i]); for (int i = 0; i < n - 1; i++) { if (s[i] != s[i + 1]) { node t = {i, i + 1, abs(a[i + 1] - a[i])}; q.push(t); } } while (q.size()) { node t = q.top(); if (vis[t.l] == 1 || vis[t.r] == 1) { q.pop(); continue; } ans[cnt][0] = t.l + 1; ans[cnt++][1] = t.r + 1; vis[t.l] = vis[t.r] = 1; q.pop(); int l = ll[t.l], r = rr[t.r]; ll[r] = l; rr[l] = r; if (l >= 0 && r <= n - 1 && s[l] != s[r]) { node tt = {l, r, abs(a[l] - a[r])}; q.push(tt); } } printf("%d\n", cnt); for (int i = 0; i < cnt; i++) printf("%d %d\n", ans[i][0], ans[i][1]); } return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
/** * Created by IntelliJ IDEA. * User: Taras_Brzezinsky * Date: 9/13/11 * Time: 5:33 PM * To change this template use File | Settings | File Templates. */ import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.IOException; import java.util.*; public class TaskA extends Thread { public TaskA() { this.input = new BufferedReader(new InputStreamReader(System.in)); this.output = new PrintWriter(System.out); this.setPriority(Thread.MAX_PRIORITY); } static class Pair implements Comparable<Pair> { int what, left, right; public Pair(int what, int left, int right) { this.what = what; this.left = left; this.right = right; } public int compareTo(TaskA.Pair o) { if (this.what == o.what) { if (this.left == o.left) { return this.right - o.right; } else { return this.left - o.left; } } else { return this.what - o.what; } } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Pair)) return false; Pair pair = (Pair) o; if (left != pair.left) return false; if (right != pair.right) return false; if (what != pair.what) return false; return true; } @Override public int hashCode() { int result = what; result = 31 * result + left; result = 31 * result + right; return result; } } private void solve() throws Throwable { int n = nextInt(); char[] gender = nextToken().toCharArray(); int[] skills = new int[n]; int[] left = new int[n]; int[] right = new int[n]; boolean[] was = new boolean[n + 1]; for (int i = 0; i < n; ++i) { skills[i] = nextInt(); left[i] = i - 1; right[i] = i + 1; } PriorityQueue<Pair> storage = new PriorityQueue<Pair>(); ArrayList<Integer> answerLeft = new ArrayList<Integer>(); ArrayList<Integer> answerRight = new ArrayList<Integer>(); for (int i = 0; i + 1 < n; ++i) { if (gender[i] != gender[i + 1]) { storage.offer(new Pair(Math.abs(skills[i] - skills[i + 1]), i, i + 1)); } } while (!storage.isEmpty()) { Pair current = storage.poll(); if (current.right == right[current.left] && !(was[current.left] || was[current.right])) { answerLeft.add(current.left + 1); answerRight.add(current.right + 1); was[current.left] = was[current.right] = true; if (left[current.left] >= 0){ right[left[current.left]] = right[current.right]; } if (right[current.right] < n){ left[right[current.right]] = left[current.left]; } current.right = right[current.right]; current.left = left[current.left]; if (current.right < n && current.left >= 0 && !(was[current.left] || was[current.right]) && gender[current.right] != gender[current.left]) { storage.offer(new Pair(Math.abs(skills[current.right] - skills[current.left]), current.left, current.right)); } } } output.println(answerLeft.size()); for (int i = 0; i < answerLeft.size(); ++i) { output.println(answerLeft.get(i) + " " + answerRight.get(i)); } } public void run() { try { solve(); } catch (Throwable e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(666); } finally { output.flush(); output.close(); } } public static void main(String[] args) { new TaskA().start(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private String nextToken() throws IOException { while (tokens == null || !tokens.hasMoreTokens()) { tokens = new StringTokenizer(input.readLine()); } return tokens.nextToken(); } static final long PRIME = 1000000009L; private BufferedReader input; private PrintWriter output; private StringTokenizer tokens = null; }
JAVA
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; set<pair<long long, pair<long long, long long> > > v; vector<pair<long long, long long> > ans; long long n, i, h[200010], g[200010], prv[200010], nxt[200010]; string s; int main() { cin >> n >> s; g[0] = g[n + 1] = 2; h[0] = -2 * 10000010; h[n + 1] = 2 * 10000010; for (i = 1; i <= n; i++) { g[i] = (s[i - 1] == 'B'); scanf("%I64d", &h[i]); } for (i = 1; i <= n; i++) { nxt[i] = i + 1; prv[i] = i - 1; } for (i = 1; i <= n + 1; i++) if (g[i] != g[i - 1]) v.insert({abs(h[i] - h[i - 1]), {i - 1, i}}); while (((*v.begin()).first < 10000010) && n) { long long l = (*v.begin()).second.first, r = (*v.begin()).second.second; n -= 2; v.erase(v.begin()); ans.push_back({l, r}); v.erase({abs(h[l] - h[r]), {l, r}}); if (g[prv[l]] != g[l]) v.erase({abs(h[prv[l]] - h[l]), {prv[l], l}}); if (g[nxt[r]] != g[r]) v.erase({abs(h[nxt[r]] - h[r]), {r, nxt[r]}}); l = prv[l]; r = nxt[r]; if (g[l] != g[r]) v.insert({abs(h[l] - h[r]), {l, r}}); nxt[l] = r; prv[r] = l; } printf("%d\n", ans.size()); for (auto it : ans) printf("%I64d %I64d\n", it.first, it.second); return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
from heapq import heappush, heappop,heapify n = int(input()) b = list(input()) a = [int(i)for i in input().split()] c = [] d = [0]*n e = [] ahead = [0]+[i for i in range(n)] after = [i+1 for i in range(n)]+[0] num = 0 for i in range(n-1): x = i y = i+1 if b[x]!=b[y]: #print('b[i]!=b[i+1]')# c.append((abs(a[x]-a[y]),x,y)) heapify(c) while c: #print('c is not NUll')# skill, cp1 ,cp2 = heappop(c) if d[cp1]+d[cp2] == 0: d[cp1],d[cp2] = 1,1 #print(cp1,cp2)# e.append(str(cp1+1)+" "+str(cp2+1)) num += 1 if cp1 > 0 and cp2 < n-1:# x = ahead[cp1] #print(x) y = after[cp2] #print(y) ahead[y] = x after[x] = y if b[x] != b[y]: heappush(c,(abs(a[x]-a[y]),x,y)) print(num) print('\n'.join(e))
PYTHON3
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; typedef struct couple { int a, b, w; } couple; bool operator<(const couple &a, const couple &b) { if (a.w == b.w) return a.a > b.a; return a.w > b.w; } couple build_couple(int a, int b, int w) { couple tmp; tmp.a = a; tmp.b = b; tmp.w = w; return tmp; } int main() { priority_queue<couple> pq; set<int> ids; vector<int> v(300000); vector<couple> cps; char s[300000]; int n; scanf("%d\n%s", &n, s); for (int i = 0; i < n; ++i) { scanf("%d", &v[i]); ids.insert(i); } for (int i = 0; i < n - 1; ++i) { if (s[i] != s[i + 1]) pq.push(build_couple(i, i + 1, abs(v[i] - v[i + 1]))); } while (!pq.empty()) { couple q = pq.top(); pq.pop(); if (ids.find(q.a) == ids.end() || ids.find(q.b) == ids.end()) continue; ids.erase(q.a); ids.erase(q.b); set<int>::iterator it = ids.lower_bound(q.a); if (it != ids.begin()) --it; set<int>::iterator it2 = ids.lower_bound(q.b); if (it != ids.end() && it2 != ids.end()) { if (s[*it] != s[*it2]) pq.push(build_couple(*it, *it2, abs(v[*it] - v[*it2]))); } cps.push_back(q); } printf("%d\n", (int)cps.size()); for (int i = 0; i < cps.size(); ++i) { printf("%d %d\n", cps[i].a + 1, cps[i].b + 1); } return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; struct couple { int i1; int i2; int diff; bool operator<(const couple& other) const { if (diff > other.diff) return 1; else if (diff < other.diff) return 0; else { if (i1 > other.i1) return 1; else return 0; } } }; int main() { priority_queue<couple> pq; vector<couple> v; int n; string s; int cnt = 0; scanf("%d", &n); cin >> s; int ara[n]; int left[n]; int right[n]; for (int i = 0; i < n; i++) { scanf("%d", &ara[i]); left[i] = i - 1; right[i] = i + 1; } for (int i = 0; i < s.size() - 1; i++) { couple p; if (s[i] != s[i + 1]) { p.i1 = i; p.i2 = i + 1; p.diff = abs(ara[i] - ara[i + 1]); pq.push(p); } } while (!pq.empty()) { couple p = pq.top(); pq.pop(); if (ara[p.i1] && ara[p.i2]) { cnt++; v.push_back(p); ara[p.i1] = 0; ara[p.i2] = 0; couple q; q.i1 = left[p.i1]; q.i2 = right[p.i2]; right[q.i1] = q.i2; left[q.i2] = q.i1; if (q.i1 >= 0 && q.i2 <= n - 1) { if (ara[q.i1] && ara[q.i2]) { if (s[q.i1] != s[q.i2]) { q.diff = abs(ara[q.i1] - ara[q.i2]); pq.push(q); } } } } } printf("%d\n", cnt); for (int i = 0; i < v.size(); i++) { printf("%d %d\n", v[i].i1 + 1, v[i].i2 + 1); } }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.Comparator; import java.util.LinkedList; import java.util.PriorityQueue; public class C45 { static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); static PrintWriter out = new PrintWriter(System.out); static int nextInt() throws IOException { in.nextToken(); return Integer.valueOf(in.sval); } static double nextDouble() throws IOException { in.nextToken(); return Double.valueOf(in.sval); } static String nextString() throws IOException { in.nextToken(); return in.sval; } static { in.ordinaryChars('0', '9'); in.wordChars('0', '9'); in.ordinaryChars('.', '.'); in.wordChars('.', '.'); in.ordinaryChars('-', '-'); in.wordChars('-', '-'); } public static void main(String[] args) throws IOException { int n = nextInt(); char[] s = nextString().toCharArray(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); PriorityQueue<int[]> q = new PriorityQueue<int[]>(2*n, new Comparator<int[]>(){ public int compare(int[] a, int[] b) { return a[0] > b[0] ? 1 : a[0] < b[0] ? -1 : a[1] > b[1] ? 1 : -1; } }); int[] next = new int[n]; for (int i = 0; i < n; i++) next[i] = i+1; int[] prev = new int[n]; for (int i = 0; i < n; i++) prev[i] = i-1; for (int i = 1; i < n; i++) if (s[i-1] != s[i]) q.offer(new int[]{Math.abs(a[i-1] - a[i]), i-1, i}); LinkedList<int[]> ans = new LinkedList<int[]>(); while (q.size() > 0) { int[] cur = q.poll(); int x = cur[1], y = cur[2]; if (next[x] != y) continue; ans.add(cur); if (prev[x] >= 0 && next[y] < n) { next[prev[x]] = next[y]; prev[next[y]] = prev[x]; if (s[prev[x]] != s[next[y]]) q.offer(new int[]{Math.abs(a[prev[x]] - a[next[y]]), prev[x], next[y]}); } else if (prev[x] < 0 && next[y] < n) { prev[next[y]] = prev[x]; } else if (prev[x] >= 0 && next[y] >= n) { next[prev[x]] = next[y]; } next[x] = prev[x] = next[y] = prev[y] = Integer.MIN_VALUE; } out.println(ans.size()); for (int[] r : ans) out.println((r[1]+1) + " " + (r[2]+1)); out.flush(); } }
JAVA
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
// practice with kaiboy import java.io.*; import java.util.*; public class CF45C extends PrintWriter { CF45C() { super(System.out); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF45C o = new CF45C(); o.main(); o.flush(); } int[] aa, ll, rr; int[] pq, iq; int cnt; boolean lt(int i, int j) { int a = Math.abs(aa[i] - aa[rr[i]]); int b = Math.abs(aa[j] - aa[rr[j]]); return a < b || a == b && i < j; } int p2(int p) { return (p *= 2) > cnt ? 0 : p < cnt && lt(iq[p + 1], iq[p]) ? p + 1 : p; } void pq_up(int i) { int j, p, q; for (p = pq[i]; (q = p / 2) > 0 && lt(i, j = iq[q]); p = q) iq[pq[j] = p] = j; iq[pq[i] = p] = i; } void pq_dn(int i) { int j, p, q; for (p = pq[i]; (q = p2(p)) > 0 && lt(j = iq[q], i); p = q) iq[pq[j] = p] = j; iq[pq[i] = p] = i; } void pq_add_last(int i) { iq[pq[i] = ++cnt] = i; } void pq_add(int i) { pq[i] = ++cnt; pq_up(i); } int pq_remove_first() { int i = iq[1], j = iq[cnt--]; if (j != i) { pq[j] = 1; pq_dn(j); } pq[i] = 0; return i; } void pq_remove(int i) { int j = iq[cnt--]; if (j != i) { pq[j] = pq[i]; pq_up(j); pq_dn(j); } pq[i] = 0; } void main() { int n = sc.nextInt(); byte[] cc = sc.next().getBytes(); aa = new int[n]; ll = new int[n]; rr = new int[n]; for (int i = 0; i < n; i++) aa[i] = sc.nextInt(); for (int i = 0; i < n; i++) { ll[i] = i - 1; rr[i] = i + 1; } pq = new int[n]; iq = new int[1 + n]; for (int i = 0; i < n - 1; i++) if (cc[i] != cc[i + 1]) pq_add_last(i); for (int p = cnt / 2; p > 0; p--) pq_dn(iq[p]); int[] xx = new int[n], yy = new int[n]; int k = 0; while (cnt > 0) { int i = pq_remove_first(), j = rr[i], l = ll[i], r = rr[j]; xx[k] = i; yy[k] = j; k++; if (l >= 0 && pq[l] != 0) pq_remove(l); if (pq[j] != 0) pq_remove(j); if (l >= 0) rr[l] = r; if (r < n) ll[r] = l; if (l >= 0 && r < n && cc[l] != cc[r]) pq_add(l); } println(k); for (int h = 0; h < k; h++) println((xx[h] + 1) + " " + (yy[h] + 1)); } }
JAVA
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; #pragma GCC optimize("O2") #pragma GCC optimize("unroll-loops") #pragma GCC target("popcnt,abm,mmx,tune=native") char sex[200010]; int val[200010]; int l[200010]; int r[200010]; struct node { int lpos; int rpos; int dis; bool operator<(const node &r) const { return dis > r.dis || dis == r.dis && lpos > r.lpos; } }; int main() { int n; while (2 == scanf("%u%s", &n, sex + 1)) { priority_queue<node> pq; node tmp; int i; int nboy = 0; for (i = 1; i <= n; i++) { l[i] = i - 1; r[i] = i + 1; if (sex[i] == 'B') { nboy++; } scanf("%u", &val[i]); } { if (nboy > (n - nboy)) nboy = (n - nboy); }; for (i = 1; i < n; i++) { if (sex[i] != sex[i + 1]) { tmp.lpos = i; tmp.rpos = i + 1; tmp.dis = abs(val[i] - val[i + 1]); pq.push(tmp); } } printf("%u\n", nboy); while (nboy--) { do { tmp = pq.top(); pq.pop(); } while (!sex[tmp.lpos] || !sex[tmp.rpos]); printf("%u %u\n", tmp.lpos, tmp.rpos); sex[tmp.lpos] = 0; sex[tmp.rpos] = 0; int lc = l[tmp.lpos]; int rc = r[tmp.rpos]; r[lc] = rc; l[rc] = lc; if ('B' ^ 'G' ^ sex[lc] ^ sex[rc]) { } else { tmp.lpos = lc; tmp.rpos = rc; tmp.dis = abs(val[lc] - val[rc]); pq.push(tmp); } } } return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; long long BigMod(long long B, long long P, long long M) { long long R = 1; while (P > 0) { if (P % 2 == 1) { R = (R * B) % M; } P /= 2; B = (B * B) % M; } return R; } struct data { int dif, L, R; bool operator<(const data &a) const { if (a.dif < dif) return 1; if (a.dif > dif) return 0; if (a.dif == dif) return a.L < L; } }; priority_queue<data> Q; set<int> st; int ara[200005]; vector<pair<int, int> > v; int main() { ios_base::sync_with_stdio(0); cin.tie(nullptr); int n; cin >> n; string str; cin >> str; for (int i = 0; i < n; i++) cin >> ara[i]; for (int i = 0; i < n; i++) st.insert(i); for (int i = 0; i < str.size() - 1; i++) if (str[i] != str[i + 1]) Q.push({((ara[i] - ara[i + 1]) < 0 ? -(ara[i] - ara[i + 1]) : (ara[i] - ara[i + 1])), i, i + 1}); while (not Q.empty()) { data A = Q.top(); Q.pop(); if (st.find(A.L) == st.end()) continue; if (st.find(A.R) == st.end()) continue; v.push_back({A.L, A.R}); st.erase(st.find(A.L)); st.erase(st.find(A.R)); auto it = st.upper_bound(A.R); auto pt = st.lower_bound(A.L); if (pt == st.begin()) continue; pt--; if (it == st.end()) continue; if (str[*pt] != str[*it]) { Q.push({((ara[*pt] - ara[*it]) < 0 ? -(ara[*pt] - ara[*it]) : (ara[*pt] - ara[*it])), *pt, *it}); } } cout << v.size() << "\n"; for (int i = 0; i < v.size(); i++) { cout << v[i].first + 1 << " " << v[i].second + 1 << "\n"; } }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
import heapq as hq n=int(input()) l=input() A=[int(i) for i in input().split()] d=[] nxt=[i+1 for i in range(n-1)] frt=[i for i in range(n-1)] now=[True for i in range(n)] for i in range(n-1): if l[i]!=l[i+1]: d+=[[abs(A[i]-A[i+1]),i,i+1]] hq.heapify(d) ans=[] while d!=[]: a,b,c=hq.heappop(d) if (now[b] and now[c]) is not True: continue else: ans+=[str(b+1)+' '+str(c+1)] now[b],now[c]=False,False if b!=0 and c!=n-1: x,y=frt[b-1],nxt[c] if l[x]!=l[y]: hq.heappush(d,[abs(A[x]-A[y]),x,y]) nxt[x],frt[y-1]=y,x print(len(ans)) print('\n'.join(ans))
PYTHON3
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
from heapq import * n = int(input()) que = input() skill = [int(i) for i in input().split()] difference = [] couple = [] left = [i - 1 for i in range(n)] right = [i + 1 for i in range(n)] for i in range(1, n): if que[i] != que[i-1]: heappush(difference, (abs(skill[i]-skill[i-1]), i-1, i)) while len(difference): dif, fir, sec = heappop(difference) if left[fir] != "None" and right[sec] != "None": couple += [str(fir + 1) + ' ' + str(sec + 1)] r = left[fir] s = right[sec] left[sec] = "None" right[fir] = "None" if not (left[fir] == -1 or right[sec] == n): right[r] = s left[s] = r if que[r] != que[s]: heappush(difference,(abs(skill[r] - skill[s]),r,s)) print(len(couple)) print('\n'.join(couple))
PYTHON3
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; long long min(long long a, long long b) { return a > b ? b : a; } int N, bnum, gnum; int L[500009], R[500009], sk[500009]; char bg[500009]; int P[500009]; struct node { long long key; int home; }; struct heap { int size; node s[500009]; void clear() { size = 0; } bool emtpy() { if (size == 0) return true; else return false; } void del(int x) { int now = x; s[now] = s[size]; size--; P[s[now].home] = now; while (now > 1) { if (s[now / 2].key > s[now].key) { swap(s[now], s[now / 2]); P[s[now].home] = now; now /= 2; P[s[now].home] = now; } else break; } while (now <= size) { if (now * 2 > size) break; else if (now * 2 == size && s[now].key > s[now * 2].key) { swap(s[now], s[now * 2]); P[s[now].home] = now; now *= 2; P[s[now].home] = now; } else { if (s[now].key <= min(s[now * 2].key, s[now * 2 + 1].key)) break; if (s[now * 2].key <= s[now * 2 + 1].key) { swap(s[now], s[now * 2]); P[s[now].home] = now; now *= 2; P[s[now].home] = now; } else { swap(s[now], s[now * 2 + 1]); P[s[now].home] = now; now = now * 2 + 1; P[s[now].home] = now; } } } } void add(long long kk, int h) { long long k = kk * 1000000 + h; int now = ++size; while (now > 1) { if (k < s[now / 2].key) { s[now] = s[now / 2]; P[s[now].home] = now; now /= 2; } else break; } s[now].key = k; s[now].home = h; P[s[now].home] = now; } } H; int main() { cin >> N; bnum = gnum = 0; bg[0] = bg[N + 1] = 'M'; for (int i = 1; i <= N; i++) { cin >> bg[i]; if (bg[i] == 'B') bnum++; else gnum++; } for (int i = 1; i <= N; i++) cin >> sk[i]; H.clear(); for (int i = 1; i <= N; i++) { L[i] = i - 1; R[i] = i + 1; if (i < N) { if (bg[i] != bg[i + 1]) H.add(abs(sk[i] - sk[i + 1]), i); } } cout << min(bnum, gnum) << "\n"; while (!H.emtpy()) { int u = H.s[1].home; cout << u << " " << R[u] << "\n"; H.del(P[u]); if (L[u] > 0 && bg[L[u]] != bg[u]) H.del(P[L[u]]); if (R[R[u]] <= N && bg[R[u]] != bg[R[R[u]]]) H.del(P[R[u]]); L[R[R[u]]] = L[u]; R[L[u]] = R[R[u]]; if (bg[L[u]] != bg[R[R[u]]] && L[u] > 0 && R[R[u]] <= N) H.add(abs(sk[L[u]] - sk[R[R[u]]]), L[u]); } return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const int MAXN = 222222; int ans[MAXN][10]; int n; int first[MAXN]; int behind[MAXN]; char str[MAXN]; bool mark[MAXN]; int a[MAXN]; struct node { int i, j; int d; bool operator<(node a) const { if (d != a.d) return d > a.d; return i > a.i; } node() {} node(int a, int b, int c) { i = a, j = b, d = c; } }; int main() { scanf("%d", &n); scanf("%s", str + 1); memset(mark, 0, sizeof mark); for (int i = 1; i <= n; i++) scanf("%d", a + i), first[i] = i - 1, behind[i] = i + 1; priority_queue<node> q; for (int i = 1; i < n; i++) { if (str[i] != str[i + 1]) { int x = abs(a[i + 1] - a[i]); q.push(node(i, i + 1, x)); } } int cnt = 0; while (!q.empty()) { node u; while (!q.empty()) { u = q.top(); q.pop(); if ((!mark[u.i]) && (!mark[u.j])) break; } int i = u.i, j = u.j; if (mark[i] || mark[j]) break; mark[i] = 1; mark[j] = 1; first[behind[j]] = first[i]; behind[first[i]] = behind[j]; ans[++cnt][0] = i; ans[cnt][1] = j; for (; i >= 1 && mark[i]; i = first[i]) ; for (; j <= n && mark[j]; j = behind[j]) ; if (i >= 1 && j <= n && str[i] != str[j]) { q.push(node(i, j, abs(a[i] - a[j]))); } } printf("%d\n", cnt); for (int i = 1; i <= cnt; i++) { printf("%d %d\n", ans[i][0], ans[i][1]); } return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; int n, m; int a[200010], b[200010]; int L[200010], R[200010]; char s[200010]; set<pair<int, int> > st; vector<pair<int, int> > ans; int h; void input() { scanf("%s", s); for (int i = 0; i < n; i++) b[i] = (s[i] == 'B' ? 1 : 2); for (int i = 0; i < n; i++) { L[i] = i - 1; R[i] = i + 1; scanf("%d", a + i); } b[n] = 3; h = n; L[0] = h; R[n - 1] = h; L[h] = n - 1; R[h] = 0; } int myabs(int x) { return x < 0 ? -x : x; } void solve() { st.clear(); ans.resize(0); for (int i = 0; i < n - 1; i++) { if (b[i] + b[i + 1] == 3) { st.insert(make_pair(myabs(a[i] - a[i + 1]), i)); } } while (st.size()) { pair<int, int> p = *st.begin(); st.erase(st.begin()); ans.push_back(make_pair(p.second, R[p.second])); if (L[p.second] != h) { int pre = L[p.second]; if (b[pre] + b[p.second] == 3) { st.erase(make_pair(myabs(a[pre] - a[p.second]), pre)); } } if (R[R[p.second]] != h) { int next = R[p.second]; if (b[next] + b[R[next]] == 3) { st.erase(make_pair(myabs(a[next] - a[R[next]]), next)); } } int pre = L[p.second]; int next = R[R[p.second]]; R[pre] = next; L[next] = pre; if (b[pre] + b[next] == 3) { st.insert(make_pair(myabs(a[pre] - a[next]), pre)); } } } void output() { printf("%d\n", ans.size()); for (int i = 0; i < ans.size(); i++) printf("%d %d\n", ans[i].first + 1, ans[i].second + 1); } int main() { while (scanf("%d", &n) != EOF) { input(); solve(); output(); } return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const int N = 200000; pair<int, pair<int, int> > ms(int a, int b, int c) { return make_pair(a, make_pair(b, c)); } int x[N]; char s[N + 1]; bool viz[N]; int m = 0; int l[N], r[N]; int r1[N], r2[N]; priority_queue<pair<int, pair<int, int> >, vector<pair<int, pair<int, int> > >, greater<pair<int, pair<int, int> > > > q; int main() { int n; scanf("%d", &n); scanf("%s", s); for (int i = 0; i < n; i++) cin >> x[i]; for (int i = 0; i < n - 1; i++) { l[i] = i - 1; r[i] = i + 1; if (s[i] != s[i + 1]) q.push(ms(abs(x[i + 1] - x[i]), i, i + 1)); } l[n - 1] = n - 2; r[n - 1] = n; while (!q.empty()) { pair<int, pair<int, int> > st = q.top(); q.pop(); int i = st.second.first; int j = st.second.second; if (viz[i] || viz[j]) continue; viz[i] = viz[j] = 1; r1[m] = i; r2[m] = j; m++; if (l[i] != -1) r[l[i]] = r[j]; if (r[j] != n) l[r[j]] = l[i]; if (l[i] != -1 && r[j] != n && s[l[i]] != s[r[j]]) q.push(ms(abs(x[l[i]] - x[r[j]]), l[i], r[j])); } cout << m << endl; for (int i = 0; i < m; i++) cout << r1[i] + 1 << ' ' << r2[i] + 1 << endl; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; int n, ka, ans[210010][7], a[210010], d, l[210010], r[210010]; pair<int, int> o; set<pair<int, pair<int, int> > > s; char c[210010]; set<pair<int, pair<int, int> > >::iterator it; pair<int, pair<int, int> > k; int abs(int a) { if (a >= 0) return a; return -a; } int main() { scanf("%d", &n); char ch; scanf("%c", &ch); ka = 0; for (int i = 0; i < n; i++) scanf("%c", &c[i]); c[n] = 'A'; for (int i = 0; i < n; i++) scanf("%d", &a[i]); for (int i = 1; i < n; i++) l[i] = i - 1; for (int i = 0; i < n - 1; i++) r[i] = i + 1; l[0] = n; r[n - 1] = n; for (int i = 0; i < n - 1; i++) { if (c[i] == 'B' && c[i + 1] == 'G') { int x = 0; x = abs(a[i] - a[i + 1]); s.insert(make_pair(x, make_pair(i, i + 1))); } if (c[i] == 'G' && c[i + 1] == 'B') { int x = 0; x = abs(a[i] - a[i + 1]); s.insert(make_pair(x, make_pair(i, i + 1))); } } while (s.size() > 0) { k = *(s.begin()); ka++; ans[ka][1] = k.second.first; ans[ka][2] = k.second.second; s.erase(s.begin()); l[r[k.second.second]] = l[k.second.first]; l[k.second.second] = l[k.second.first]; r[l[k.second.first]] = r[k.second.second]; r[k.second.first] = r[k.second.second]; o.first = l[k.second.first]; o.second = k.second.first; d = abs(a[o.first] - a[o.second]); it = s.find(make_pair(d, o)); if (it != s.end()) s.erase(it); o.first = k.second.second; o.second = r[k.second.second]; d = abs(a[o.first] - a[o.second]); it = s.find(make_pair(d, o)); if (it != s.end()) s.erase(it); o.first = l[k.second.first]; o.second = r[k.second.second]; d = abs(a[o.first] - a[o.second]); if ((c[o.first] == 'G' && c[o.second] == 'B') || (c[o.first] == 'B' && c[o.second] == 'G')) s.insert(make_pair(d, o)); } printf("%d\n", ka); for (int i = 1; i <= ka; i++) printf("%d %d\n", ans[i][1] + 1, ans[i][2] + 1); return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; string p; long long s[200007], l[200007], r[200007]; bool vis[200007]; struct couple { long long l, r, d; couple(long long l, long long r, long long d) : l(l), r(r), d(d) {} }; bool operator<(const couple &l, const couple &r) { if (l.d == r.d) return l.l > r.l; return l.d > r.d; } priority_queue<couple> Q; int main() { memset(vis, false, sizeof(vis)); long long N; scanf("%lld", &N); cin >> p; p = "*" + p; for (long long i = (1); i < (N + 1); i++) { scanf("%lld", &s[i]); l[i] = i - 1; r[i] = i + 1; } for (long long i = (1); i < (N); i++) { if (p[i] != p[i + 1]) { Q.push(couple(i, i + 1, abs(s[i] - s[i + 1]))); } } vector<pair<long long, long long> > ans; while (!Q.empty()) { couple T = Q.top(); Q.pop(); long long L = T.l, R = T.r, L_ = l[L], R_ = r[R]; if (vis[L] || vis[R]) continue; ans.push_back(pair<long long, long long>(L, R)); vis[L] = true; vis[R] = true; r[L_] = R_; l[R_] = L_; if (p[L_] != p[R_] && L_ > 0 && R_ <= N && R_ > 0 && L_ <= N) { Q.push(couple(L_, R_, abs(s[L_] - s[R_]))); } } cout << ans.size() << endl; for (long long i = (0); i < (ans.size()); i++) { printf("%lld ", ans[i].first); printf("%lld\n", ans[i].second); } }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
import java.io.*; import java.util.*; import java.math.*; public class Dancing { int L[] = new int[200001]; int R[] = new int[200001]; boolean isBoy[] = new boolean[200001]; int rating[] = new int[200001]; TreeSet<Pair> set = new TreeSet<Pair>(); Dancing() throws Exception { Scanner in = new Scanner(System.in); int N = in.nextInt(); int nb = 0; String line = in.next(); for(int i = 0; i < line.length(); i++) { if(line.charAt(i) == 'G') { isBoy[i] = false; } else { isBoy[i] = true; nb++; } rating[i] = in.nextInt(); if(i > 0 && (isBoy[i] ^ isBoy[i-1])) { set.add(new Pair(i-1, i, Math.abs(rating[i] - rating[i-1]))); } L[i] = i-1; R[i] = i+1; } int ret = Math.min(nb, N-nb); int test = 0; StringBuilder out = new StringBuilder(""); while(!set.isEmpty()) { // ret++; test++; Pair at = set.first(); set.remove(at); if(L[at.i] >= 0 && (isBoy[L[at.i]] ^ isBoy[at.i]) ) { set.remove(new Pair(L[at.i], at.i, Math.abs(rating[L[at.i]] - rating[at.i]))); } if(L[at.i] >= 0) { R[L[at.i]] = R[at.j]; } if(R[at.j] < N && (isBoy[R[at.j]] ^ isBoy[at.j]) ) { set.remove(new Pair(at.j, R[at.j], Math.abs(rating[R[at.j]] - rating[at.j]))); } if(R[at.j] < N) { L[R[at.j]] = L[at.i]; } if(L[at.i] >= 0 && R[at.j] < N && (isBoy[L[at.i]] ^ isBoy[R[at.j]])) { set.add(new Pair(L[at.i], R[at.j], Math.abs(rating[L[at.i]] - rating[R[at.j]]))); } L[at.i] = -1; R[at.i] = N; L[at.j] = -1; R[at.j] = N; out.append((at.i+1) + " " + (at.j+1) + "\n"); } System.out.println(ret); System.out.println(out); } public class Pair implements Comparable<Pair> { int i, j, dif; Pair(int a, int b, int d) { i = a; j = b; dif = d; } public int compareTo(Pair b) { if(this.dif == b.dif) { if(this.i == b.i) { return this.j - b.j; } else return this.i - b.i; } else return this.dif - b.dif; } public String toString() { return "(" + i +", " + j + " = " + dif + ")"; } } public static void main(String args[]) throws Exception { new Dancing(); } }
JAVA
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
import heapq n=int(input()) g=input() a=[int(i) for i in input().split()] h=[] heapq.heapify(h) prev=[i-1 for i in range(0,n)] next=[i+1 for i in range(0,n)] d=[0]*n; r=[] for i in range(0,n-1): if(g[i]!=g[i+1]): heapq.heappush(h,(abs(a[i]-a[i+1]),i,i+1)) while h : aa,ii,jj=heapq.heappop(h) if(d[ii]==0) and (d[jj]==0): r.append(str(ii+1)+' '+str(jj+1)); d[ii]=1; d[jj]=1; pp=prev[ii]; nn=next[jj]; if(pp>=0) and (nn<n): next[pp]=nn; prev[nn]=pp; if g[nn]!=g[pp]: heapq.heappush(h,(abs(a[nn]-a[pp]),pp,nn)) print(len(r)); print('\n'.join(r));
PYTHON3
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; int sayi_s; string str = "-"; string ph; priority_queue<pair<int, pair<int, int> > > pq; vector<pair<int, int> > komsular; vector<int> sayilar; int e_s, k_s; int main() { cin >> sayi_s; cin >> ph; str += (ph + "-"); sayilar.push_back(-1); for (int i = 1; i <= sayi_s; i++) { sayilar.push_back(0); cin >> sayilar[i]; if (str[i] == 'B') { e_s++; } else { k_s++; } } for (int i = 0; i < sayi_s + 3; i++) { komsular.push_back(make_pair(i - 1, i + 1)); } for (int i = 1; i <= sayi_s - 1; i++) { if ((str[i] == 'B' && str[i + 1] == 'G') || (str[i] == 'G' && str[i + 1] == 'B')) { pq.push( make_pair(-abs(sayilar[i] - sayilar[i + 1]), make_pair(-i, -i - 1))); } } printf("%d\n", min(e_s, k_s)); while (pq.size()) { if (komsular[-pq.top().second.first].second == -pq.top().second.second && komsular[-pq.top().second.second].first == -pq.top().second.first) { cout << -pq.top().second.first << " " << -pq.top().second.second << "\n"; int a, b; b = komsular[-pq.top().second.second].second; a = komsular[-pq.top().second.first].first; komsular[-pq.top().second.first] = make_pair(-2, -2); komsular[-pq.top().second.second] = make_pair(-2, -2); pq.pop(); komsular[a].second = b; komsular[b].first = a; if ((str[a] == 'B' && str[b] == 'G') || (str[a] == 'G' && str[b] == 'B')) { pq.push(make_pair(-abs(sayilar[a] - sayilar[b]), make_pair(-a, -b))); } } else { pq.pop(); } } return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; bool ch[200001]; struct info { long long df, l, r; }; struct cmp { bool operator()(const info& a, const info& b) { if (a.df == b.df) return a.l > b.l; return a.df > b.df; } }; int main() { ios_base::sync_with_stdio(0); long long int i, j, x, n, cnt = 0, m, y, k, g, flg, lft, rgt; priority_queue<info, vector<info>, cmp> pq; string in, a; in += 'a'; cin >> n >> a; in += a; long long sk[n + 1], lp[n + 1], rp[n + 1]; info d; vector<pair<long long, long long> > ans; for (i = 1; i <= n; i++) { cin >> sk[i]; } if (n == 1) { cout << 0; return 0; } if (in[1] != in[2]) d.df = abs(sk[1] - sk[2]); else d.df = 1e9; d.l = 1; d.r = 2; pq.push(d); lp[1] = -1; rp[1] = 2; if (n > 2) { if (in[n] != in[n - 1]) d.df = abs(sk[n] - sk[n - 1]); else d.df = 1e9; d.l = n - 1; d.r = n; } lp[n] = n - 1; rp[n] = -1; for (i = 2; i <= n - 1; i++) { if (in[i] != in[i - 1]) d.df = abs(sk[i] - sk[i - 1]); else d.df = 1e9; d.l = i - 1; d.r = i; pq.push(d); if (in[i] != in[i + 1]) d.df = abs(sk[i] - sk[i + 1]); else d.df = 1e9; d.l = i; d.r = i + 1; pq.push(d); lp[i] = i - 1; rp[i] = i + 1; } while (!pq.empty()) { d = pq.top(); pq.pop(); if (ch[d.l] || ch[d.r]) continue; if (d.df > 1e8) break; lft = lp[d.l]; rgt = rp[d.r]; ans.push_back(make_pair(d.l, d.r)); ch[d.l] = ch[d.r] = 1; if (lft != -1 && rgt != -1) { if (in[lft] != in[rgt]) d.df = abs(sk[lft] - sk[rgt]); else d.df = 1e9; d.l = lft; d.r = rgt; pq.push(d); } if (lft != -1) rp[lft] = rgt; if (rgt != -1) lp[rgt] = lft; } cout << ans.size() << endl; if (ans.size() > 0) { for (i = 0; i <= ans.size() - 1; i++) { cout << ans[i].first << " " << ans[i].second << endl; } } }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const int M = 300100; struct partners { int diff, l, r; partners(int a = 0, int b = 0, int c = 0) { diff = a; l = b; r = c; } bool operator<(const partners &d) const { if (diff == d.diff) return l > d.l; else return diff > d.diff; } }; priority_queue<partners> q; set<int> pos; int visited[M], A[M]; char typ[M]; vector<pair<int, int> > ans; int main() { int n, i, j, k, temp; scanf("%d", &n); scanf("%s", typ); for (i = 0; i < n; i++) scanf("%d", &A[i]), pos.insert(i); for (i = 1; i < n; i++) { if (typ[i] != typ[i - 1]) { q.push(partners(abs(A[i] - A[i - 1]), i - 1, i)); } } memset((visited), (false), sizeof(visited)); while (!q.empty()) { partners u = q.top(); q.pop(); if (visited[u.l] || visited[u.r]) continue; visited[u.l] = visited[u.r] = true; pos.erase(u.l); pos.erase(u.r); ans.push_back(make_pair(u.l + 1, u.r + 1)); set<int>::iterator lt = pos.upper_bound(u.l), rt = pos.upper_bound(u.r); if (lt != pos.begin()) { lt--; if (rt != pos.end()) { if (typ[*lt] != typ[*rt]) { q.push(partners(abs(A[*lt] - A[*rt]), *lt, *rt)); } } } } printf("%d\n", ans.size()); for (i = 0; i < ans.size(); i++) printf("%d %d\n", ans[i].first, ans[i].second); return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
import javax.swing.*; import java.io.*; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import java.util.Map.Entry; public class Main implements Runnable { static final int MOD = (int) 1e9 + 7; static final int MI = (int) 1e9; static final long ML = (long) 1e18; static final Reader in = new Reader(); static final PrintWriter out = new PrintWriter(System.out); StringBuilder answer = new StringBuilder(); public static void main(String[] args) { new Thread(null, new Main(), "persefone", 1 << 32).start(); } @Override public void run() { solve(); printf(); flush(); } void solve() { int n = in.nextInt(); char[] sex = in.next().toCharArray(); int[] skills = in.nextIntArray(n); NavigableSet<Integer> index = IntStream.range(0, n).boxed().collect(Collectors.toCollection(TreeSet::new)); PriorityQueue<Item> heap = new PriorityQueue<>(); for (int i = 1; i < n; i++) { if (sex[i] != sex[i - 1]) { heap.add(new Item(i - 1, i, Math.abs(skills[i - 1] - skills[i]))); } } boolean[] check = new boolean[n]; Arrays.fill(check, true); List<int[]> ans = new ArrayList<>(); while (true) { if (heap.isEmpty()) break; Item item = heap.poll(); int left = item.left; int right = item.right; if (!check[left] || !check[right]) { continue; } ans.add(new int[] {left + 1, right + 1}); index.remove(left); index.remove(right); check[left] = check[right] = false; Integer before = index.floor(left); if (before != null) { Integer after = index.ceiling(right); if (after != null) { if (sex[before] != sex[after]) { heap.add(new Item(before, after, Math.abs(skills[before] - skills[after]))); } } } } printf(ans.size()); for (int[] res : ans) printf(res); } static class Item implements Comparable<Item> { private int left, right, diff; public Item(int left, int right, int diff) { this.left = left; this.right = right; this.diff = diff; } @Override public int compareTo(Item that) { return this.diff == that.diff ? this.left - that.left : this.diff - that.diff; } @Override public String toString() { return "Item{" + "left=" + left + ", right=" + right + ", diff=" + diff + '}'; } } static class Fenwick { private int n; private long[] sum; public Fenwick(int n) { this.n = n + 10; this.sum = new long[n + 10]; } public void update(int i, int v) { for (; i < n; i += i & -i) { sum[i] += v; } } long sum(int i) { long res = 0; for (; i > 0; i -= i & -i) { res += sum[i]; } return res; } long sum(int i, int j) { return sum(j) - sum(i - 1); } } static class SegmentTreeSum { private int n; private int[] a, sum; public SegmentTreeSum(int[] a, int n) { this.n = n; this.a = a; this.sum = new int[4 * n + 4]; build(1, 0, n - 1); } public void build(int currentVertex, int currentLeft, int currentRight) { if (currentLeft == currentRight) sum[currentVertex] = a[currentLeft]; else { int mid = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1; build(doubleVex, currentLeft, mid); build(doubleVex + 1, mid + 1, currentRight); sum[currentVertex] = sum[doubleVex] + sum[doubleVex + 1]; } } public void update(int currentVertex, int currentLeft, int currentRight, int pos, int value) { if (currentLeft == currentRight) sum[currentVertex] = a[pos] = value; else { int mid = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1; if (pos <= mid) update(doubleVex, currentLeft, mid, pos, value); else update(doubleVex + 1, mid + 1, currentRight, pos, value); sum[currentVertex] = sum[doubleVex] + sum[doubleVex + 1]; } } public void update(int pos, int value) { update(1, 0, n - 1, pos, value); } public int sum(int currentVertex, int currentLeft, int currentRight, int left, int right) { if (currentLeft > right || currentRight < left) return 0; else if (left <= currentLeft && currentRight <= right) return sum[currentVertex]; int mid = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1; return sum(doubleVex, currentLeft, mid, left, right) + sum(doubleVex + 1, mid + 1, currentRight, left, right); } public int sum(int left, int right) { return sum(1, 0, n - 1, left, right); } public int kth(int currentVertex, int currentLeft, int currentRight, int k) { if (k > sum[currentVertex]) return -1; if (currentLeft == currentRight) return currentLeft; int mid = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1; if (k <= sum[doubleVex]) return kth(doubleVex, currentLeft, mid, k); else return kth(doubleVex + 1, mid + 1, currentRight, k - sum[doubleVex]); } public int kth(int k) { return kth(1, 0, n - 1, k); } } static class TreeSetTree { private int n; private int[] a; private NavigableSet<Integer>[] set; public TreeSetTree(int[] a, int n) { this.n = n; this.a = a; this.set = Stream.generate(TreeSet::new).limit(4 * n + 4).toArray(NavigableSet[]::new); build(1, 0, n - 1); } void merge(NavigableSet<Integer> z, NavigableSet<Integer> x, NavigableSet<Integer> y) { z.addAll(x); z.addAll(y); } public void build(int currentVertex, int currentLeft, int currentRight) { if (currentLeft == currentRight) set[currentVertex].add(a[currentLeft]); else { int mid = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1; build(doubleVex, currentLeft, mid); build(doubleVex + 1, mid + 1, currentRight); merge(set[currentVertex], set[doubleVex], set[doubleVex + 1]); } } public void update(int currentVertex, int currentLeft, int currentRight, int pos, int value) { set[currentVertex].remove(a[pos]); set[currentVertex].add(value); if (currentLeft == currentRight) { a[pos] = value; } else { int mid = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1; if (pos <= mid) update(doubleVex, currentLeft, mid, pos, value); else update(doubleVex + 1, mid + 1, currentRight, pos, value); } } public void update(int pos, int value) { update(1, 0, n - 1, pos, value); } public int get(int currentVertex, int currentLeft, int currentRight, int left, int right, int k) { if (currentLeft > right || currentRight < left) return 0; else if (left <= currentLeft && currentRight <= right) { Integer floor = set[currentVertex].floor(k); return floor == null ? 0 : floor; } int mid = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1; return Math.max(get(doubleVex, currentLeft, mid, left, right, k), get(doubleVex + 1, mid + 1, currentRight, left, right, k)); } public int get(int left, int right, int k) { return get(1, 0, n - 1, left, right, k); } } static class ListUtils { static int lowerBound(List<Integer> list, int l, int r, int k) { int m = 0, ans = r; while (l < r) if (list.get(m = l + r >> 1) >= k) ans = r = m; else l = m + 1; return ans; } static int upperBound(List<Integer> list, int l, int r, int k) { int m = 0, ans = r; while (l < r) if (list.get(m = l + r >> 1) > k) ans = r = m; else l = m + 1; return ans; } static int amountOfNumbersEqualTo(List<Integer> list, int l, int r, int k) { return upperBound(list, l, r, k) - lowerBound(list, l, r, k); } static int amountOfNumbersEqualTo(List<Integer> list, int k) { return upperBound(list, 0, list.size(), k) - lowerBound(list, 0, list.size(), k); } } static class ArrayUtils { static int lowerBound(int[] a, int l, int r, int k) { int m = 0, ans = r; while (l < r) if (a[m = l + r >> 1] >= k) ans = r = m; else l = m + 1; return ans; } static int upperBound(int[] a, int l, int r, int k) { int m = 0, ans = r; while (l < r) if (a[m = l + r >> 1] > k) ans = r = m; else l = m + 1; return ans; } static int lowerBound(int[] a, int k) { return lowerBound(a, 0, a.length, k); } static int upperBound(int[] a, int k) { return upperBound(a, 0, a.length, k); } static void compressed(int[] a, int n) { int[] b = a.clone(); Arrays.sort(b); for (int i = 0; i < n; i++) { a[i] = lowerBound(b, a[i]) + 1; } } } static class IntegerUtils { // returns { gcd(a,b), x, y } such that gcd(a,b) = a*x + b*y static long[] euclid(long a, long b) { long x = 1, y = 0, x1 = 0, y1 = 1, t; while (b != 0) { long q = a / b; t = x; x = x1; x1 = t - q * x1; t = y; y = y1; y1 = t - q * y1; t = b; b = a - q * b; a = t; } return a > 0 ? new long[]{a, x, y} : new long[]{-a, -x, -y}; } static int[] generatePrimesUpTo(int n) { boolean[] composite = new boolean[n + 1]; for (int i = 2; i <= n; i++) { for (int j = i; 1l * i * j <= n; j++) { composite[i * j] = true; } } return IntStream.rangeClosed(2, n).filter(i -> !composite[i]).toArray(); } static int[] smallestFactor(int n) { int[] sf = new int[n + 1]; for (int i = 2; i <= n; i++) { if (sf[i] == 0) { sf[i] = i; for (int j = i; 1l * i * j <= n; j++) { if (sf[i * j] == 0) { sf[i * j] = i; } } } } return sf; } static int phi(int n) { int result = n; for (int i = 2; 1l * i * i <= n; i++) { if (n % i == 0) { while (n % i == 0) n /= i; result -= result / i; } } if (n > 1) result -= result / n; return result; } static long phi(long n) { // n <= 10 ^ 12; long result = n; for (int i = 2; 1l * i * i <= n; i++) { if (n % i == 0) { while (n % i == 0) n /= i; result -= result / i; } } if (n > 1) result -= result / n; return result; } static long[] n_thFiboNaCi(long n, int p) { // f[n + k] = f[n + 1].f[k] + f[n].f[k - 1] if (n == 0) return new long[]{0, 1}; long[] a = n_thFiboNaCi(n >> 1, p); long c = (2 * a[1] - a[0] + p) % p * a[0] % p; long d = (a[1] * a[1] % p + a[0] * a[0] % p) % p; if (n % 2 == 0) return new long[]{c, d}; else return new long[]{d, (c + d) % p}; } static long modPow(int base, int exponential, int p) { if (exponential == 0) return 1; long x = modPow(base, exponential >> 1, p) % p; return exponential % 2 == 0 ? x * x % p : x * x % p * base % p; } static long modPow(long base, int exponential, int p) { if (exponential == 0) return 1; long x = modPow(base, exponential >> 1, p) % p; return exponential % 2 == 0 ? x * x % p : x * x % p * base % p; } static long modPow(long base, long exponential, int p) { if (exponential == 0) return 1; long x = modPow(base, exponential >> 1, p) % p; return exponential % 2 == 0 ? x * x % p : x * x % p * base % p; } static long[] generateFactorialArray(int n, int p) { long[] factorial = new long[n + 1]; factorial[0] = 1; for (int i = 1; i <= n; i++) factorial[i] = (factorial[i - 1] * i) % p; return factorial; } static long cNkModP(long[] factorial, int n, int k, int p) { return factorial[n] * modPow(factorial[k], p - 2, p) % p * modPow(factorial[n - k], p - 2, p) % p; } static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } } static class SparseTableMax { private int n, blocks; private int[] log, data; private int[][] max; public SparseTableMax(int[] data, int n) { this.n = n; this.data = data; this.log = new int[n + 1]; for (int i = 2; i <= n; i++) { log[i] = log[i >> 1] + 1; } this.blocks = log[n]; this.max = new int[n][blocks + 1]; for (int i = 0; i < n; i++) { max[i][0] = data[i]; } build(); } int calc(int a, int b) { return Math.max(a, b); } void build() { for (int j = 1; j <= blocks; j++) { for (int i = 0; i + (1 << j) <= n; i++) { max[i][j] = calc(max[i][j - 1], max[i + (1 << j - 1)][j - 1]); } } } int getMax(int l, int r) { int k = log[r - l + 1]; return calc(max[l][k], max[r - (1 << k) + 1][k]); } } static class DSU { protected int vertex, countCC; protected int[] id, size; public DSU(int vertex) { this.vertex = vertex; this.id = IntStream.range(0, vertex).toArray(); this.size = new int[vertex]; Arrays.fill(size, 1); countCC = vertex; } int find(int i) { return id[i] == i ? i : (id[i] = find(id[i])); } void unite(int i, int j) { int x = find(i); int y = find(j); if (x == y) return; countCC--; if (size[x] > size[y]) { id[y] = id[x]; size[x] += size[y]; size[y] = 0; return; } id[x] = id[y]; size[y] += size[x]; size[x] = 0; } boolean isConnected(int i, int j) { return find(i) == find(j); } int connectedComponents() { return countCC; } } void printf() { out.print(answer); } void close() { out.close(); } void flush() { out.flush(); } void printf(Stream<?> str) { str.forEach(o -> add(o, " ")); add("\n"); } void printf(Object... obj) { printf(false, obj); } void printfWithDescription(Object... obj) { printf(true, obj); } private void printf(boolean b, Object... obj) { if (obj.length > 1) { for (int i = 0; i < obj.length; i++) { if (b) add(obj[i].getClass().getSimpleName(), " - "); if (obj[i] instanceof Collection<?>) { printf((Collection<?>) obj[i]); } else if (obj[i] instanceof int[][]) { printf((int[][]) obj[i]); } else if (obj[i] instanceof long[][]) { printf((long[][]) obj[i]); } else if (obj[i] instanceof double[][]) { printf((double[][]) obj[i]); } else printf(obj[i]); } return; } if (b) add(obj[0].getClass().getSimpleName(), " - "); printf(obj[0]); } void printf(Object o) { if (o instanceof int[]) printf(Arrays.stream((int[]) o).boxed()); else if (o instanceof char[]) printf(new String((char[]) o)); else if (o instanceof long[]) printf(Arrays.stream((long[]) o).boxed()); else if (o instanceof double[]) printf(Arrays.stream((double[]) o).boxed()); else if (o instanceof boolean[]) { for (boolean b : (boolean[]) o) add(b, " "); add("\n"); } else add(o, "\n"); } void printf(int[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(long[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(double[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(boolean[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(Collection<?> col) { printf(col.stream()); } <T, K> void add(T t, K k) { if (t instanceof Collection<?>) { ((Collection<?>) t).forEach(i -> add(i, " ")); } else if (t instanceof Object[]) { Arrays.stream((Object[]) t).forEach(i -> add(i, " ")); } else add(t); add(k); } <T> void add(T t) { answer.append(t); } @SuppressWarnings("unchecked") <T extends Comparable<? super T>> T min(T... t) { if (t.length == 0) return null; T m = t[0]; for (int i = 1; i < t.length; i++) if (t[i].compareTo(m) < 0) m = t[i]; return m; } @SuppressWarnings("unchecked") <T extends Comparable<? super T>> T max(T... t) { if (t.length == 0) return null; T m = t[0]; for (int i = 1; i < t.length; i++) if (t[i].compareTo(m) > 0) m = t[i]; return m; } static class Pair<K extends Comparable<? super K>, V extends Comparable<? super V>> implements Comparable<Pair<K, V>> { private K k; private V v; Pair(K k, V v) { this.k = k; this.v = v; } @SuppressWarnings("unchecked") @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof Pair)) return false; Pair<K, V> p = (Pair<K, V>) o; return k.compareTo(p.k) == 0 && v.compareTo(p.v) == 0; } @Override public int hashCode() { int hash = 31; hash = hash * 89 + k.hashCode(); hash = hash * 89 + v.hashCode(); return hash; } @Override public int compareTo(Pair<K, V> pair) { return k.compareTo(pair.k) == 0 ? v.compareTo(pair.v) : k.compareTo(pair.k); } @Override public Pair<K, V> clone() { return new Pair<K, V>(this.k, this.v); } @Override public String toString() { return String.valueOf(k).concat(" ").concat(String.valueOf(v)).concat("\n"); } } static class Reader { private BufferedReader br; private StringTokenizer st; Reader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { try { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } long nextLong() { return Long.parseLong(next()); } String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } }
JAVA
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
from heapq import heapify, heappop, heappush n=int(input()) s=input() a=list(map(int,input().split())) p=[i-1 for i in range(n)] nx=[i+1 for i in range(n)] f=[1 for i in range(n)] d=[(abs(a[i]-a[i+1]),i,i+1) for i in range(n-1) if s[i]!=s[i+1]] heapify(d) ans=[] while d: t,pp,pn=heappop(d) if (f[pp] and f[pn]): ans.append(''.join([str(pp+1), ' ', str(pn+1)])) f[pp],f[pn]=0,0 if (pp==0) or (pn==n-1): continue ppp,npn=p[pp],nx[pn] nx[ppp],p[npn]=npn,ppp if (s[ppp]!=s[npn]): heappush(d,(abs(a[ppp]-a[npn]),ppp,npn)) print(len(ans)) print('\n'.join(ans))
PYTHON3
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; assert(1 <= n && n <= (int)(2e5)); string sex; cin >> sex; assert(sex.size() == n); for (int i = 0; i < n; ++i) { assert(sex[i] == 'B' || sex[i] == 'G'); } vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; assert(1 <= a[i] && a[i] <= (int)(1e7)); } vector<int> pre(n), nxt(n); priority_queue<pair<int, pair<int, int> >, vector<pair<int, pair<int, int> > >, greater<pair<int, pair<int, int> > > > pq; for (int i = 0; i < n; ++i) { pre[i] = i - 1; nxt[i] = i + 1; if (i > 0 && sex[i - 1] != sex[i]) { pq.push(make_pair(abs(a[i - 1] - a[i]), make_pair(i - 1, i))); } } vector<bool> mark(n, true); vector<pair<int, int> > result; while (!pq.empty()) { int i = pq.top().second.first; int j = pq.top().second.second; pq.pop(); if (mark[i] && mark[j]) { mark[i] = false; mark[j] = false; result.push_back(make_pair(i, j)); i = pre[i]; j = nxt[j]; if (i != -1) { nxt[i] = j; } if (j != n) { pre[j] = i; } if (i != -1 && j != n && sex[i] != sex[j] && mark[i] && mark[j]) { pq.push(make_pair(abs(a[i] - a[j]), make_pair(i, j))); } } } cout << result.size() << endl; for (int i = 0; i < result.size(); ++i) { cout << result[i].first + 1 << " " << result[i].second + 1 << endl; } return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; class Skill { public: int s, l, r; Skill(int _s, int _l, int _r) : s(_s), l(_l), r(_r) {} friend inline bool operator<(const Skill& o1, const Skill& o2) { if (o1.s != o2.s) return !(o1.s < o2.s); return !(o1.l < o2.l); } }; int main() { int n, i, j, i2, j2; vector<char> bg; vector<int> a; set<int> lst; priority_queue<Skill> q; vector<pair<int, int> > ans; scanf("%d", &n); bg.assign(n, 0); scanf("%c", &bg[0]); for_each(bg.begin(), bg.end(), [](char& o) { scanf("%c", &o); }); a.assign(n, 0); for_each(a.begin(), a.end(), [](int& o) { scanf("%d", &o); }); lst.insert(0); for (int i = 1; i != n; ++i) { if (bg[i] != bg[i - 1]) q.push(Skill(abs(a[i - 1] - a[i]), i - 1, i)); lst.insert(i); } while (!q.empty()) { i = q.top().l; j = q.top().r; q.pop(); if (lst.find(i) == lst.end() || lst.find(j) == lst.end()) continue; ans.push_back(make_pair(i, j)); if (lst.find(i) != lst.begin() && lst.find(j) != --lst.end()) { i2 = *(--lst.find(i)); j2 = *(++lst.find(j)); if (bg[i2] != bg[j2]) q.push(Skill(abs(a[i2] - a[j2]), i2, j2)); } lst.erase(i); lst.erase(j); } printf("%d\n", (int)ans.size()); for_each(ans.begin(), ans.end(), [](const pair<int, int>& o) { printf("%d %d\n", o.first + 1, o.second + 1); }); return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
# It seems the running time depends much on the condition of the server. from heapq import heappush,heappop,heapify n=int(input()) symbols=input() skl=list(map(int,input().split())) LMap=[i-1 for i in range(n+1)] RMap=[i+1 for i in range(n+1)] LMap[1],RMap[n]=1,n h=[] res=[] cnt=0 #B=symbols.count("B") #N=min(n-B,B) ind=[True]*(n+1) h=[] for i in range(n-1) : if symbols[i]!=symbols[i+1] : h.append((abs(skl[i]-skl[i+1]),i+1,i+2)) heapify(h) i=0 while h : d,L,R=heappop(h) if ind[L] and ind[R] : cnt+=1 ind[L],ind[R]=False,False res.append(str(L)+" "+str(R)) if L==1 or R==n : continue L,R=LMap[L],RMap[R] RMap[L],LMap[R]=R,L if symbols[L-1]!=symbols[R-1] : heappush(h,(abs(skl[L-1]-skl[R-1]),L,R)) #assert cnt==N print(cnt) for i in res : print(i)
PYTHON3
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const int N = 200005; struct P { int l, r, v; } o; bool operator<(const P &x, const P &y) { return x.v == y.v ? x.l > y.l : x.v > y.v; } priority_queue<P> q; bool u[N]; char s[N]; int a[N], L[N], R[N]; vector<pair<int, int> > r; int main() { int n, i; scanf("%d", &n); scanf("%s", s); for (i = 0; i < n; i++) scanf("%d", a + i); for (i = 0; i < n; i++) { L[i] = i - 1; R[i] = i + 1; } for (i = 0; i < n - 1; i++) { if (s[i] != s[i + 1]) { o.l = i; o.r = i + 1; o.v = abs(a[i] - a[i + 1]); q.push(o); } } memset(u, true, sizeof(u)); while (!q.empty()) { P fr = q.top(); q.pop(); while ((!u[fr.l] || !u[fr.r]) && !q.empty()) { fr = q.top(); q.pop(); } if (!u[fr.l] || !u[fr.r]) break; u[fr.l] = u[fr.r] = false; r.push_back(make_pair(fr.l, fr.r)); R[L[fr.l]] = R[fr.r]; L[R[fr.r]] = L[fr.l]; if (L[fr.l] >= 0 && L[fr.l] < n && R[fr.r] >= 0 && R[fr.r] < n && s[L[fr.l]] != s[R[fr.r]]) { o.l = L[fr.l]; o.r = R[fr.r]; o.v = abs(a[L[fr.l]] - a[R[fr.r]]); q.push(o); } } printf("%d\n", r.size()); for (i = 0; i < r.size(); i++) printf("%d %d\n", r[i].first + 1, r[i].second + 1); return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; char tmp[200005]; int n; inline int abs(int n) { if (n > 0) { return n; } else { return -n; } } struct Node { int left, right; int skill; Node() {} Node(int l, int r, int s) { left = l; right = r; skill = s; } bool operator<(Node o) const { if (skill == o.skill) { return left > o.left; } else { return skill > o.skill; } } bool isLegal() { if (tmp[left] != 'X' && tmp[right] != 'X') { return true; } else { return false; } } } data[200005]; int main() { while (scanf("%d", &n) != EOF) { scanf("%s", tmp); for (int i = 0; i < n; i++) { scanf("%d", &data[i].skill); data[i].left = i - 1; data[i].right = i + 1; } priority_queue<Node> quu; vector<Node> out; for (int i = 1; i < n; i++) { if (tmp[i] != tmp[i - 1]) { quu.push(Node(i - 1, i, abs(data[i].skill - data[i - 1].skill))); } } while (quu.empty() == false) { Node p = quu.top(); quu.pop(); if (p.isLegal()) { out.push_back(Node(p.left, p.right, 0)); tmp[p.left] = tmp[p.right] = 'X'; int right = data[data[p.left].left].right = data[p.right].right; int left = data[data[p.right].right].left = data[p.left].left; if (left != -1 && right != n && tmp[left] != tmp[right]) { quu.push( Node(left, right, abs(data[left].skill - data[right].skill))); } } } printf("%d\n", out.size()); for (vector<Node>::iterator it = out.begin(); it != out.end(); it++) { printf("%d %d\n", it->left + 1, it->right + 1); } } return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
import heapq n = int(input()) line = str(input()) a = [int(i) for i in input().split()] diff = [] couples = [] left = [i-1 for i in range(n)] right = [i+1 for i in range(n)] for i in range(n-1): if line[i] != line[i+1]: heapq.heappush(diff,(abs(a[i]-a[i+1]),i,i+1)) while len(diff)>0: d,l,r = heapq.heappop(diff) if left[l] != None and right[r] != None: couples.append(str(l+1)+' '+str(r+1)) left[r] = None right[l] = None new_l = left[l] new_r = right[r] if new_l != -1 and new_r != n: left[new_r] = new_l right[new_l] = new_r if line[new_l] != line[new_r]: heapq.heappush(diff,(abs(a[new_l]-a[new_r]),new_l,new_r)) print(len(couples)) print('\n' .join(couples))
PYTHON3
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
# -*- coding: utf-8 -*- """ Created on Sat May 7 11:48:38 2016 @author: Alex """ import heapq, sys q = [] cnt = 0 n = int(input()) sex = input() a = list(map(int, input().split())) l = [i-1 for i in range(n)] #η”Ÿζˆε·¦ζŒ‡ι’ˆεˆ—θ‘¨ r = [i+1 for i in range(n)] #η”Ÿζˆε³ζŒ‡ι’ˆεˆ—θ‘¨ for i in range(n-1): if sex[i] != sex[i+1]: heapq.heappush(q, (abs(a[i] - a[i+1]), i, i+1)) cnt += 1 ans = [] while cnt > 0: t, i, j = heapq.heappop(q) cnt -= 1 if r[i] == -1 or r[j] == -1: continue ans.append('%d %d' % (i+1, j+1)) u, v = l[i], r[j] r[i] = r[j] = -1 if u >= 0: r[u] = v if v < n: l[v] = u if u >= 0 and v < n and sex[u] != sex[v]: heapq.heappush(q, (abs(a[u] - a[v]), u, v)) cnt += 1 sys.stdout.write(str(len(ans)) + '\n' + '\n'.join(ans) + '\n')\
PYTHON3
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; template <class T> T gcd(T a, T b) { return a == 0 ? b : gcd(b % a, a); } template <class T> string tostring(T a) { ostringstream os; os << a; return os.str(); } int toint(string a) { istringstream is(a); int p; is >> p; return p; } long long toll(string a) { istringstream is(a); long long p; is >> p; return p; } string s; vector<int> sk; vector<int> ne, fr; vector<bool> used; int main() { int n; cin >> n >> s; sk.resize(n); for (int i = 0; i < n; i++) cin >> sk[i]; ne.resize(n); fr.resize(n); for (int i = 0; i < n - 1; i++) ne[i] = i + 1, fr[i + 1] = i; ne[n - 1] = -1; fr[0] = -1; used.resize(n, false); set<pair<int, pair<int, int> > > se; for (int i = 0; i < n - 1; i++) if (s[i] != s[i + 1]) se.insert(make_pair(abs(sk[i] - sk[i + 1]), make_pair(i, i + 1))); vector<pair<int, int> > res; while (se.size() > 0) { pair<int, pair<int, int> > x = *se.begin(); se.erase(se.begin()); if (used[x.second.first] || used[x.second.second]) continue; res.push_back(x.second); if (fr[x.second.first] != -1) ne[fr[x.second.first]] = ne[x.second.second]; if (ne[x.second.second] != -1) fr[ne[x.second.second]] = fr[x.second.first]; if (fr[x.second.first] != -1 && ne[x.second.second] != -1 && s[fr[x.second.first]] != s[ne[x.second.second]]) se.insert(make_pair(abs(sk[fr[x.second.first]] - sk[ne[x.second.second]]), make_pair(fr[x.second.first], ne[x.second.second]))); used[x.second.first] = used[x.second.second] = true; } cout << res.size() << endl; for (int i = 0; i < res.size(); i++) cout << res[i].first + 1 << " " << res[i].second + 1 << endl; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const int N = 200010; struct node { int v, x, y; bool operator<(const node &b) const { return v > b.v || (v == b.v && min(x, y) > min(b.x, b.y)); } }; int a[N], pre[N], suc[N], ans[N][2], n; bool boy[N], out[N]; priority_queue<node> Q; char s[N]; int main() { scanf("%d", &n); scanf("%s", s + 1); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); for (int i = 1; i <= n; i++) boy[i] = (s[i] == 'B'); for (int i = 1; i <= n; i++) pre[i] = i - 1, suc[i] = i + 1; for (int i = 1; i < n; i++) if (boy[i] ^ boy[i + 1]) Q.push((node){abs(a[i] - a[i + 1]), i, i + 1}); int num = 0; while (!Q.empty()) { int x = Q.top().x, y = Q.top().y; Q.pop(); if (out[x] || out[y]) continue; out[x] = out[y] = 1; num++; ans[num][0] = x, ans[num][1] = y; if (x > y) swap(x, y); int i = pre[x], j = suc[y]; pre[j] = i; suc[i] = j; if (i < 1 || j > n) continue; if (boy[i] ^ boy[j]) { Q.push((node){abs(a[i] - a[j]), i, j}); } } printf("%d\n", num); for (int i = 1; i <= num; i++) printf("%d %d\n", ans[i][0], ans[i][1]); return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; struct node { int x, y, d; bool operator<(const node &t) const { return (d > t.d) || ((d == t.d) && (x > t.x)); } } temp; int n, r[200005], x[200005], y[200005], X, Y, out, a[100005][2]; char s[200005]; bool b[200005]; priority_queue<node> q; int main() { scanf("%d%s", &n, s); for (int i = 0; i < n; i++) { scanf("%d", &r[i]); x[i] = i - 1; y[i] = i + 1; b[i] = true; } for (int i = 1; i < n; i++) { if (s[i] != s[i - 1]) { temp.x = i - 1; temp.y = i; temp.d = abs(r[i] - r[i - 1]); q.push(temp); } } out = 0; while (!q.empty()) { temp = q.top(); X = temp.x; Y = temp.y; q.pop(); if ((b[X]) && (b[Y])) { b[X] = false; b[Y] = false; a[out][0] = X; a[out][1] = Y; out++; if (x[X] >= 0) { y[x[X]] = y[Y]; } if (y[Y] < n) { x[y[Y]] = x[X]; } if ((x[X] >= 0) && (y[Y] < n) && (s[x[X]] != s[y[Y]])) { temp.x = x[X]; temp.y = y[Y]; temp.d = abs(r[x[X]] - r[y[Y]]); q.push(temp); } } } printf("%d\n", out); for (int i = 0; i < out; i++) { printf("%d %d\n", a[i][0] + 1, a[i][1] + 1); } return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5; set<pair<int, int> > vset; vector<pair<int, int> > rvec; int a[N], n, pre[N], nxt[N]; char str[N]; int main() { scanf("%d", &n); scanf("%s", str); for (int i = 0; i < n; i++) scanf("%d", a + i); for (int i = 0; i < n; i++) { pre[i] = i - 1; nxt[i] = i + 1; } for (int i = 1; i < n; i++) { if (str[i] == str[i - 1]) continue; vset.insert(make_pair(abs(a[i] - a[i - 1]), i)); } while (!vset.empty()) { int d = (*vset.begin()).second, u, v; vset.erase(vset.begin()); v = pre[pre[d]], u = nxt[d]; nxt[v] = u; pre[u] = v; vset.erase(make_pair(abs(a[u] - a[d]), u)); vset.erase(make_pair(abs(a[pre[d]] - a[v]), pre[d])); if (v >= 0 && u < n && str[v] != str[u]) vset.insert(make_pair(abs(a[u] - a[v]), u)); rvec.push_back(make_pair(pre[d] + 1, d + 1)); } printf("%d\n", rvec.size()); for (int i = 0; i < rvec.size(); i++) printf("%d %d\n", rvec[i].first, rvec[i].second); }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5; int n, t = 0, l, r, a[N], v[N], L[N], R[N]; char s[N]; struct cmp { bool operator()(pair<int, int> &r, pair<int, int> &q) const { if (abs(a[r.first] - a[r.second]) == abs(a[q.first] - a[q.second])) return r.first > q.first; return abs(a[r.first] - a[r.second]) > abs(a[q.first] - a[q.second]); } }; priority_queue<pair<int, int>, vector<pair<int, int> >, cmp> pq; int main() { cin >> n; scanf("%s", s + 1); for (int i = 1; i <= n; i++) { scanf("%d", a + i), L[i] = i - 1, R[i] = i + 1; if (i != 1 && s[i] != s[i - 1]) pq.push({i - 1, i}); if (s[i] == 'G') t++; } t = min(t, n - t); cout << t << endl; while (t) { pair<int, int> c = pq.top(); pq.pop(); if (v[c.first] || v[c.second]) continue; cout << c.first << " " << c.second << endl; l = L[c.first], r = R[c.second]; if (l > 0 && r <= n && s[l] != s[r]) pq.push({l, r}); L[r] = l, R[l] = r; v[c.first] = 1, v[c.second] = 1; t--; } }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
import heapq,sys q=[] c=0 n=int(input()) s=input() a=list(map(int,input().split())) l=[i-1 for i in range(n)] r=[i+1 for i in range(n)] for i in range(n-1): if s[i]!=s[i+1]: heapq.heappush(q,(abs(a[i]-a[i+1]),i,i+1)) c+=1 ans=[] while c>0: t,i,j=heapq.heappop(q) c-=1 if r[i]==-1 or r[j]==-1: continue ans.append('%d %d'%(i+1,j+1)) u,v=l[i],r[j] r[i]=r[j]=-1 if u>=0: r[u]=v if v<n: l[v]=u if u>=0 and v<n and s[u]!=s[v]: heapq.heappush(q,(abs(a[u]-a[v]),u,v)) c+=1 sys.stdout.write(str(len(ans))+'\n'+'\n'.join(ans)+'\n')
PYTHON3
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
import heapq, sys q = [] cnt = 0 n = int(input()) sex = input() a = list(map(int, input().split())) l = [i-1 for i in range(n)] r = [i+1 for i in range(n)] for i in range(n-1): if sex[i] != sex[i+1]: heapq.heappush(q, (abs(a[i] - a[i+1]), i, i+1)) cnt += 1 ans = [] while cnt > 0: t, i, j = heapq.heappop(q) cnt -= 1 if r[i] == -1 or r[j] == -1: continue ans.append('%d %d' % (i+1, j+1)) u, v = l[i], r[j] r[i] = r[j] = -1 if u >= 0: r[u] = v if v < n: l[v] = u if u >= 0 and v < n and sex[u] != sex[v]: heapq.heappush(q, (abs(a[u] - a[v]), u, v)) cnt += 1 sys.stdout.write(str(len(ans)) + '\n' + '\n'.join(ans) + '\n')
PYTHON3
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const int mod = 1e9 + 7; int dx[] = {-1, 1, 0, 0}; int dy[] = {0, 0, -1, 1}; int32_t main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n; cin >> n; string s; cin >> s; vector<int> v(n); vector<int> l(n, -1), r(n, -1); set<pair<int, pair<int, int>>> st; for (int i = 0; i < n; i++) { cin >> v[i]; if (i > 0) l[i] = i - 1; if (i < n - 1) r[i] = i + 1; } for (int i = 1; i < n; i++) { if (s[i - 1] != s[i]) { st.insert({abs(v[i] - v[i - 1]), {i - 1, i}}); } } vector<pair<int, int>> ans; while (st.size()) { pair<int, pair<int, int>> p = (*st.begin()); ans.push_back(p.second); st.erase(st.begin()); int lf = l[p.second.first]; int rt = r[p.second.second]; if (lf == -1 || rt == -1) { if (lf == -1 && rt != -1) { l[rt] = -1; if (s[p.second.second] != s[rt]) { st.erase({abs(v[p.second.second] - v[rt]), {p.second.second, rt}}); } } else if (rt == -1 && lf != -1) { r[lf] = -1; if (s[p.second.first] != s[lf]) { st.erase({abs(v[p.second.first] - v[lf]), {lf, p.second.first}}); } } continue; } if (s[p.second.first] != s[lf]) { st.erase({abs(v[p.second.first] - v[lf]), {lf, p.second.first}}); } if (s[p.second.second] != s[rt]) { st.erase({abs(v[p.second.second] - v[rt]), {p.second.second, rt}}); } r[lf] = rt; l[rt] = lf; if (s[lf] != s[rt]) { st.insert({abs(v[lf] - v[rt]), {lf, rt}}); } } cout << ans.size() << "\n"; for (auto i : ans) { cout << i.first + 1 << " " << i.second + 1 << "\n"; } }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> std::mt19937 rng( (int)std::chrono::steady_clock::now().time_since_epoch().count()); const int ms = 200200; int a[ms]; bool dead[ms]; std::string str; struct Event { int i, j; Event(int a = -1, int b = -1) { i = a, j = b; } bool operator>(const Event &o) const { return std::pair<int, int>(abs(a[i] - a[j]), std::min(i, j)) > std::pair<int, int>(abs(a[o.i] - a[o.j]), std::min(o.i, o.j)); } }; int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(NULL); int n; std::cin >> n; std::cin >> str; std::set<int> alive; for (int i = 0; i < n; i++) { alive.insert(i); std::cin >> a[i]; } std::priority_queue<Event, std::vector<Event>, std::greater<Event>> hp; for (int i = 0; i + 1 < n; i++) { if (str[i] != str[i + 1]) { hp.push(Event(i, i + 1)); } } std::vector<std::pair<int, int>> ans; while (!hp.empty()) { auto event = hp.top(); hp.pop(); if (dead[event.i] || dead[event.j]) continue; dead[event.i] = dead[event.j] = true; int i = event.i, j = event.j; alive.erase(i); alive.erase(j); auto itr = alive.lower_bound(j); auto itl = itr; if (itr != alive.end() && itr != alive.begin()) { itl--; if (str[*itl] != str[*itr]) { hp.push(Event(*itl, *itr)); } } ans.emplace_back(i + 1, j + 1); } std::cout << ans.size() << '\n'; for (auto wtf : ans) std::cout << wtf.first << ' ' << wtf.second << '\n'; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; vector<pair<int, int> > v; set<pair<int, int> > s; int A[200005], L[200005], R[200005], n, i, a, b, c, d; char str[200005]; int main() { cin >> n >> str + 1; for (i = 1; i <= n; i++) { cin >> A[i]; R[i] = i + 1; L[i] = i - 1; if (i > 1 && str[i] != str[i - 1]) s.insert(make_pair(abs(A[i] - A[i - 1]), i - 1)); } while (s.size()) { i = (*s.begin()).second; a = L[i]; b = i; c = R[b]; d = R[c]; s.erase(s.begin()); v.push_back(make_pair(b, c)); if (d <= n && str[c] != str[d]) s.erase(s.find(make_pair(abs(A[c] - A[d]), c))); if (a && str[a] != str[b]) s.erase(s.find(make_pair(abs(A[a] - A[b]), a))); if (a && d <= n && str[a] != str[d]) s.insert(make_pair(abs(A[a] - A[d]), a)); R[a] = d; L[d] = a; } cout << v.size() << endl; for (i = 0; i < v.size(); i++) cout << v[i].first << " " << v[i].second << endl; return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; struct node { int ll; int y; int d; friend bool operator<(const node p, const node q) { if (p.d == q.d) return p.y > q.y; else return p.d > q.d; } } t; int l[200010]; int r[200010]; int b[200010]; int g[2]; int skill[200010]; int main() { char cc; int n; while (scanf("%d", &n) != EOF) { getchar(); memset(g, 0, sizeof(g)); memset(b, -1, sizeof(b)); memset(l, -1, sizeof(l)); memset(r, -1, sizeof(r)); memset(skill, 0, sizeof(skill)); for (int i = 0; i < n; i++) { scanf("%c", &cc); if (cc == 'B') { b[i] = 0; g[0]++; } else { b[i] = 1; g[1]++; } } for (int i = 0; i < n; i++) { scanf("%d", &skill[i]); l[i] = i - 1; r[i] = i + 1; } priority_queue<node> qq; for (int i = 1; i < n; i++) { if (b[i] != b[i - 1]) { t.d = abs(skill[i] - skill[i - 1]); t.y = i; t.ll = i - 1; qq.push(t); } } int num = min(g[0], g[1]); printf("%d\n", num); while (num--) { while (!qq.empty()) { node cur = qq.top(); qq.pop(); if ((r[cur.ll] != -1) && (r[cur.y] != -1)) { printf("%d %d", cur.ll + 1, cur.y + 1); if ((l[cur.ll] != -1) && r[cur.y] < n && r[cur.y] > -1 && (b[l[cur.ll]] + b[r[cur.y]] == 1)) { t.ll = l[cur.ll]; t.y = r[cur.y]; t.d = abs(skill[l[cur.ll]] - skill[r[cur.y]]); qq.push(t); } r[l[cur.ll]] = r[cur.y]; l[r[cur.y]] = l[cur.ll]; r[cur.ll] = -1; r[cur.y] = -1; printf("\n"); } } } } return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#Code by Yijie Xia, submitted for testing the OJ import heapq as hq n=int(input()) s=input() a=list(map(int,input().split())) pre=[i-1 for i in range(n)] nxt=[i+1 for i in range(n)] free=[1 for i in range(n)] line=[(abs(a[i]-a[i+1]),i,i+1) for i in range(n-1) if s[i]!=s[i+1]] hq.heapify(line) ans=[] while line: t,ppre,pnxt=hq.heappop(line) if free[ppre] and free[pnxt]: ans.append(str(ppre+1)+' '+str(pnxt+1)) free[ppre],free[pnxt]=0,0 if ppre==0 or pnxt==n-1: continue preppre,nxtpnxt=pre[ppre],nxt[pnxt] nxt[preppre],pre[nxtpnxt]=nxtpnxt,preppre if s[preppre]!=s[nxtpnxt]: hq.heappush(line,(abs(a[preppre]-a[nxtpnxt]),preppre,nxtpnxt)) print(len(ans)) print('\n'.join(ans))
PYTHON3
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; const int MAXN = 2 * 1e5 + 5; char s[MAXN]; int a[MAXN]; set<pair<int, int> > Q; set<int> S; vector<pair<int, int> > ans; int main() { int n; cin >> n; for (int i = 0; i < n; i++) cin >> s[i]; for (int i = 0; i < n; i++) S.insert(i); for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n - 1; i++) { if (s[i] == 'B' && s[i + 1] == 'G') Q.insert(pair<int, int>(abs(a[i] - a[i + 1]), i)); if (s[i] == 'G' && s[i + 1] == 'B') Q.insert(pair<int, int>(abs(a[i] - a[i + 1]), i)); } while (!Q.empty()) { pair<int, int> P = (*Q.begin()); Q.erase(Q.begin()); set<int>::iterator it = S.find(P.second); int prev = -1, nxt = -1, now = P.second, now2 = -1; it++; now2 = *it; it--; ans.push_back(pair<int, int>(now, now2)); if (it != S.begin()) { it--; prev = *it; it++; } it++; it++; if (it != S.end()) { nxt = *it; } S.erase(now); S.erase(now2); if (prev != -1) Q.erase(pair<int, int>(abs(a[prev] - a[now]), prev)); if (nxt != -1) Q.erase(pair<int, int>(abs(a[nxt] - a[now2]), now2)); if (prev != -1 && nxt != -1) { if ((s[prev] == 'G' && s[nxt] == 'B') || (s[prev] == 'B' && s[nxt] == 'G')) { Q.insert(pair<int, int>(abs(a[prev] - a[nxt]), prev)); } } } cout << ans.size() << endl; for (int i = 0; i < (int)ans.size(); i++) cout << ans[i].first + 1 << " " << ans[i].second + 1 << endl; return 0; }
CPP
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing. Input The first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up. Output Print the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Examples Input 4 BGBG 4 2 4 3 Output 2 3 4 1 2 Input 4 BBGG 4 6 1 5 Output 2 2 3 1 4 Input 4 BGBB 1 1 2 3 Output 1 1 2
2
9
#include <bits/stdc++.h> using namespace std; set<pair<int, pair<int, int> > > dist; set<pair<int, int> > s; char c[222222]; int a[222222]; int n; int main() { scanf("%d", &n); scanf("%s", &c); int c1 = 0, c2 = 0; for (int(i) = 0; (i) < (n); ++(i)) { scanf("%d", &a[i]); if (c[i] == 'B') { s.insert(make_pair(i, 0)); ++c1; } else { s.insert(make_pair(i, 1)); ++c2; } } s.insert(make_pair(-1, -1)); s.insert(make_pair(n, n)); for (int(i) = 0; (i) < (n - 1); ++(i)) if (c[i] != c[i + 1]) dist.insert(make_pair(abs(a[i] - a[i + 1]), make_pair(i, i + 1))); printf("%d\n", min(c1, c2)); while ((int)dist.size()) { pair<int, pair<int, int> > p = *dist.begin(); dist.erase(dist.begin()); set<pair<int, int> >::iterator i = s.lower_bound(make_pair(p.second.first, -1)); if (i->first != p.second.first) continue; i = s.lower_bound(make_pair(p.second.second, -1)); if (i->first != p.second.second) continue; printf("%d %d\n", p.second.first + 1, p.second.second + 1); s.erase(s.lower_bound(make_pair(p.second.first, -1))); s.erase(s.lower_bound(make_pair(p.second.second, -1))); set<pair<int, int> >::iterator it = s.lower_bound(make_pair(p.second.first, -1)); --it; if (it != s.begin()) { set<pair<int, int> >::iterator it2 = s.lower_bound(make_pair(p.second.first, -1)); if (it2->first != n) { if (it2->second != it->second) { dist.insert(make_pair(abs(a[it->first] - a[it2->first]), make_pair(it->first, it2->first))); } } } } return 0; }
CPP