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> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n; cin >> n; string s; cin >> s; vector<int> a(n); for (int &x : a) cin >> x; set<int> X; for (int i = 0; i < n; i++) X.insert(i); map<int, pair<int, int>> mp; set<pair<int, int>> S; int c = 0; for (int i = 1; i < n; i++) { if (s[i] == s[i - 1]) continue; S.insert({abs(a[i] - a[i - 1]), c}); mp[c] = {i - 1, i}; c++; } vector<pair<int, int>> ans; while (!S.empty()) { auto p = *S.begin(); S.erase(S.begin()); int idx = p.second; int l = mp[idx].first, r = mp[idx].second; if (X.find(l) == X.end() || X.find(r) == X.end()) { if (X.find(l) == X.end()) { auto it1 = X.lower_bound(l); if (it1 == X.begin()) continue; l = *prev(it1); } if (X.find(r) == X.end()) { auto it2 = X.lower_bound(r); if (it2 == X.end()) continue; r = *it2; } if (s[l] != s[r]) { S.insert({abs(a[l] - a[r]), idx}); mp[idx] = {l, r}; } continue; } ans.push_back({l + 1, r + 1}); X.erase(l); X.erase(r); auto it1 = X.upper_bound(l); auto it2 = X.upper_bound(r); if (it1 == X.begin() || it2 == X.end()) continue; it1 = prev(it1); l = *it1, r = *it2; if (s[l] != s[r]) { S.insert({abs(a[l] - a[r]), idx}); mp[idx] = {l, r}; } } cout << ans.size() << "\n"; for (auto p : ans) cout << p.first << " " << p.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> using namespace std; template <class T> inline T gcd(T a, T b) { if (a < 0) return gcd(-a, b); if (b < 0) return gcd(a, -b); return (b == 0) ? a : gcd(b, a % b); } template <class T> inline T lcm(T a, T b) { if (a < 0) return lcm(-a, b); if (b < 0) return lcm(a, -b); return a * (b / gcd(a, b)); } template <class T> inline T sqr(T x) { return x * x; } template <class T> T power(T N, T P) { return (P == 0) ? 1 : N * power(N, P - 1); } const long long INF64 = (long long)1E16; int distsq(int x1, int y1, int x2, int y2) { return sqr(x1 - x2) + sqr(y1 - y2); } double dist2d(double x1, double y1, double x2, double y2) { return sqrt(sqr(x1 - x2) + sqr(y1 - y2)); } long long toInt64(string s) { long long r = 0; istringstream sin(s); sin >> r; return r; } double LOG(long long N, long long B) { return (log10l(N)) / (log10l(B)); } string itoa(long long a) { if (a == 0) return "0"; string ret; for (long long i = a; i > 0; i = i / 10) ret.push_back((i % 10) + 48); reverse(ret.begin(), ret.end()); return ret; } vector<string> token(string a, string b) { const char *q = a.c_str(); while (count(b.begin(), b.end(), *q)) q++; vector<string> oot; while (*q) { const char *e = q; while (*e && !count(b.begin(), b.end(), *e)) e++; oot.push_back(string(q, e)); q = e; while (count(b.begin(), b.end(), *q)) q++; } return oot; } int isvowel(char s) { s = tolower(s); if (s == 'a' || s == 'e' || s == 'i' || s == 'o' || s == 'u') return 1; return 0; } int Set(int N, int pos) { return N = N | (1 << pos); } int reset(int N, int pos) { return N = N & ~(1 << pos); } int check(int N, int pos) { return (N & (1 << pos)); } int toggle(int N, int pos) { if (check(N, pos)) return N = reset(N, pos); return N = Set(N, pos); } void pbit(int N) { printf("("); for (int i = 10; i >= 0; i--) { bool x = check(N, i); cout << x; } puts(")"); } string s; int w[200102]; struct node { int d; int i, j; node(int d1, int i1, int j1) { d = d1; i = i1; j = j1; } bool operator<(const node &p) const { if (d == p.d) { if (i == p.i) return j < p.j; return i < p.i; } return d < p.d; } }; set<node> ms; int L[200102], R[200102]; int main() { int n; cin >> n; cin >> s; for (int i = 0; i < n; i++) cin >> w[i]; for (int i = 0; i < n; i++) { L[i] = i - 1; R[i] = i + 1; } for (int i = 0; i < n - 1; i++) { if (s[i] != s[i + 1]) { int d = abs(w[i] - w[i + 1]); ms.insert(node(d, i, i + 1)); } } bool taken[200102] = {0}; vector<pair<int, int> > v; while (!ms.empty()) { node top = *ms.begin(); ms.erase(ms.begin()); if (taken[top.i]) continue; if (taken[top.j]) continue; taken[top.i] = 1; taken[top.j] = 1; v.push_back(pair<int, int>(top.i + 1, top.j + 1)); int i2 = L[top.i]; int j2 = R[top.j]; if (i2 >= 0) R[i2] = j2; if (j2 < n) L[j2] = i2; if (i2 >= 0 and j2 < n and s[i2] != s[j2]) { int d = abs(w[i2] - w[j2]); ms.insert(node(d, i2, j2)); } } cout << v.size() << endl; for (int i = 0; i < (int)v.size(); i++) cout << v[i].first << " " << v[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 MAXN = 10 + 200000; int n; struct pnt { int c, u, v; pnt(int _c = 0, int _u = 0, int _v = 0) : c(_c), u(_u), v(_v) {} bool operator<(const pnt& op) const { if (c != op.c) return c < op.c; if (u != op.u) return u < op.u; return v < op.v; } }; set<pnt> qq; char s[MAXN]; int a[MAXN]; int nxt[MAXN], lst[MAXN]; void setLink(int u) { nxt[lst[u]] = nxt[u]; lst[nxt[u]] = lst[u]; } int cnt = 0; pair<int, int> ans[MAXN]; bool vis[MAXN]; int main() { scanf("%d\n", &n); scanf("%s\n", s + 1); for (int i = 1; i <= n; ++i) { scanf("%d", a + i); } for (int i = 0; i <= n; ++i) { nxt[i] = i + 1; lst[i] = i - 1; } qq.clear(); memset(vis, 0, sizeof vis); for (int i = 2; i <= n; ++i) if (s[i] != s[i - 1]) { qq.insert(pnt(abs(a[i] - a[i - 1]), i - 1, i)); } while (!qq.empty()) { pnt top = *qq.begin(); qq.erase(qq.begin()); if (vis[top.u] || vis[top.v]) continue; ans[cnt++] = make_pair(top.u, top.v); setLink(top.u); vis[top.u] = 1; setLink(top.v); vis[top.v] = 1; int u = lst[top.u]; int v = nxt[top.v]; if (u >= 1 && v <= n && !vis[u] && !vis[v] && s[u] != s[v]) { qq.insert(pnt(abs(a[u] - a[v]), u, v)); } } printf("%d\n", cnt); for (int i = 0; i < cnt; ++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; int le[250000]; int ri[250000]; int arr[250000]; bool mark[250000]; priority_queue<pair<int, pair<int, int> > > pq; vector<pair<int, int> > v; int checkle(int x) { if (le[x] == x) return x; return le[x] = checkle(le[x]); } int checkri(int x) { if (ri[x] == x) return x; return ri[x] = checkri(ri[x]); } const int INF = 1e9; string s; bool diff(int x, int y) { return s[x - 1] != s[y - 1]; } int main() { int n; scanf("%d", &n); cin >> s; for (int i = 1; i <= n; i++) cin >> arr[i]; for (int i = 1; i <= n; i++) { le[i] = ri[i] = i; if (s[i - 1] == 'G') { if (i != 1) { if (s[i - 2] == 'B') pq.push( make_pair(-abs(arr[i] - arr[i - 1]), make_pair(-i, -(i - 1)))); } if (i != n && s[i] == 'B') { if (s[i] == 'B') pq.push( make_pair(-abs(arr[i] - arr[i + 1]), make_pair(-i, -(i + 1)))); } } } le[n + 1] = ri[n + 1] = n + 1; memset(mark, false, sizeof(mark)); while (!pq.empty()) { int val = -pq.top().first; int gi = -pq.top().second.first; int boy = -pq.top().second.second; pq.pop(); if (gi == 0 || boy == n + 1 || diff(gi, boy) == false || mark[gi] == true || mark[boy] == true) { continue; } v.push_back(make_pair(min(gi, boy), max(gi, boy))); le[gi] = checkle(gi - 1); ri[gi] = checkri(gi + 1); le[boy] = checkle(boy - 1); ri[boy] = checkri(boy + 1); if (diff(checkle(le[gi]), checkri(ri[boy])) == true) { int l = checkle(le[gi]); int r = checkri(ri[boy]); int i = l; if (s[l - 1] == 'G' && r != n + 1) { pq.push(make_pair(-abs(arr[l] - arr[r]), make_pair(-l, -r))); } if (s[r - 1] == 'G' && l != 0) { pq.push(make_pair(-abs(arr[l] - arr[r]), make_pair(-r, -l))); } } mark[boy] = true; mark[gi] = true; } printf("%d\n", v.size()); for (int i = 0; i < v.size(); i++) { printf("%d %d\n", v[i].first, v[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.util.Comparator; import java.util.PriorityQueue; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class C { public static void main(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); char[] arr2 = in.next().toCharArray(); char[] arr = new char[n+2]; for( int i = 0; i < n; i++){ arr[i+1] = arr2[i]; } int[] prev = new int[n+2]; int[] skill= new int[n+2]; int[] next = new int[n+2]; boolean[] marked = new boolean[n+2]; triple[] ts = new triple[2*n]; PriorityQueue<triple> S = new PriorityQueue<triple>(2*n, new Comparator<triple>() { @Override public int compare(triple o1, triple o2) { if( o1.d == o2.d) return o1.l - o2.l; return o1.d - o2.d; } }); int j = 0; for( int i = 1 ; i <= n; i++){ skill[i] = in.nextInt(); prev[i] = i-1; next[i] = i+1; if( i > 1 && arr[i] != arr[i-1] ){ ts[j++] = new triple(i-1 , i , skill[i] - skill[i-1]); S.add(ts[j-1]); } } //System.out.println("size" + S.size()); StringBuffer sb = new StringBuffer(); int count = 0; while( count < n/2){ triple c = S.poll(); if( c == null) break; if( marked[c.l] || marked[c.r]){ continue; } sb.append(c.l + " " + c.r); sb.append("\n"); marked[c.l] = true; marked[c.r] = true; count++; prev[next[c.r]] = prev[c.l]; next[prev[c.l]] = next[c.r]; if( next[c.r] <= n && prev[c.l] >= 1 && (arr[next[c.r]] != arr[prev[c.l]])){ S.add(new triple(prev[c.l] , next[c.r] , skill[next[c.r]] - skill[prev[c.l]])); } //System.out.println("size" + S.size()); } System.out.println(count); System.out.print(sb.toString()); } } class triple{ int l; int r; int d; triple( int l , int r , int d){ this.l = l; this.r = r; this.d = Math.abs(d); } }
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; class W { public: int c; int l; W() {} W(int a, int b) { c = a; l = b; } bool operator<(const W &q) const { return (c < q.c) || (c == q.c && l < q.l); } bool operator==(const W &q) const { return c == q.c && l == q.l; } }; class T { public: int l, r, B; T() {} T(int b, int c, int d) { l = b; r = c; B = d; } }; set<W> Set; vector<T> a; vector<int> cost; int main() { int n; scanf("%d\n", &n); cost.resize(n); string str; getline(cin, str); for (int(i) = 0; (i) < (n); ++(i)) scanf("%d", &cost[i]); for (int(i) = 0; (i) < (n); ++(i)) { a.push_back(T(i - 1, i + 1, (str[i] == 'B' ? 1 : 0))); } a.push_back(T(n, n, 1)); a[0].l = n; a[n - 1].r = n; for (int(i) = 0; (i) < (n - 1); ++(i)) { if (a[i].B ^ a[i + 1].B) Set.insert(W(abs(cost[i] - cost[i + 1]), i)); } vector<pair<int, int> > ans; while (!Set.empty()) { W t = *(Set.begin()); Set.erase(Set.begin()); int f = t.l; if (a[f].l < n && (a[a[f].l].B ^ a[f].B)) { set<W>::iterator it = Set.find(W(abs(cost[f] - cost[a[f].l]), a[f].l)); if (it == Set.end()) { assert(false); } Set.erase(it); } int s = a[t.l].r; if (a[s].r < n && (a[a[s].r].B ^ a[s].B)) { set<W>::iterator it = Set.find(W(abs(cost[s] - cost[a[s].r]), s)); if (it == Set.end()) { assert(false); } Set.erase(it); } a[a[f].l].r = a[s].r; a[a[s].r].l = a[f].l; ans.push_back(pair<int, int>(f, s)); s = a[s].r; f = a[f].l; if (s < n && f < n && a[s].B ^ a[f].B) Set.insert(W(abs(cost[s] - cost[f]), f)); } printf("%d\n", ((int)(ans).size())); for (int(i) = 0; (i) < (((int)(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; const long long N = 2e5 + 7; long long l[N], r[N]; long long a[N]; bool used[N]; signed main() { ios_base::sync_with_stdio(0); cin.tie(0); long long n; cin >> n; string second; cin >> second; for (long long i = 0; i < n; ++i) cin >> a[i]; set<pair<long long, long long> > ms; for (long long i = 0; i < n; ++i) { l[i] = i - 1; r[i] = i + 1; } r[n] = n; for (long long i = 0; i < n - 1; ++i) { if (second[i] != second[i + 1]) { ms.insert(make_pair(abs(a[i] - a[i + 1]), i)); } } vector<pair<long long, long long> > ans; while (ms.size()) { long long i = ms.begin()->second; ms.erase(ms.begin()); if (used[i] || used[r[i]]) continue; ans.push_back(make_pair(i, r[i])); used[i] = used[r[i]] = 1; long long tl = l[i]; long long tr = r[r[i]]; ms.erase(make_pair(abs(a[tl] - a[i]), tl)); ms.erase(make_pair(abs(a[tr] - a[r[i]]), r[i])); if (tl != -1) r[tl] = tr; if (tr != n) l[tr] = tl; if (tl != -1 && tr != n && second[tl] != second[tr]) { ms.insert(make_pair(abs(a[tl] - a[tr]), tl)); } } cout << ans.size() << '\n'; for (auto e : ans) cout << e.first + 1 << ' ' << e.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; set<pair<int, int> > S; set<pair<int, int> >::iterator it; int a[220000], prv[220000], nxt[220000]; char s[220000]; int main() { int n, i, j, l, r; cin >> n >> s; for (i = 1; i <= n; i++) cin >> a[i]; for (i = 1; i <= n; i++) prv[i] = i - 1, nxt[i] = i + 1; for (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()) { it = S.begin(); i = it->second, j = nxt[i]; l = prv[i], r = nxt[j]; if (l > 0 && s[l - 1] != s[i - 1]) S.erase(make_pair(abs(a[l] - a[i]), l)); if (r <= n && s[r - 1] != s[j - 1]) S.erase(make_pair(abs(a[r] - a[j]), j)); if (l > 0 && r <= n && s[l - 1] != s[r - 1]) 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); } n = ans.size(); cout << n << endl; for (i = 0; i < n; 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
import java.util.*; import java.io.*; /* 6 BBGBGG 6 4 3 7 5 1 */ public class Main { 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))); StringTokenizer s = new StringTokenizer(br.readLine()); int n=Integer.parseInt(s.nextToken()); s = new StringTokenizer(br.readLine()); String str=s.nextToken(); s = new StringTokenizer(br.readLine()); int ar[]=new int[n]; int count=0; int l[]=new int[n]; int r[]=new int[n]; for(int i=0;i<n;i++) { ar[i]=Integer.parseInt(s.nextToken()); if(str.charAt(i)=='B') count++; l[i]=i-1; r[i]=i+1; } pw.println(Math.min(count, n-count)); PriorityQueue<Node>pq=new PriorityQueue<>((a,b)->(a.ti==b.ti)?a.fi-b.fi:a.ti-b.ti); for(int i=0;i<n-1;i++) { if(str.charAt(i)!=str.charAt(i+1)) pq.add(new Node(i,i+1,Math.abs(ar[i]-ar[i+1]))); } boolean visited[]=new boolean[n]; while(!pq.isEmpty()) { Node tmp=pq.poll(); if(!visited[tmp.fi] && !visited[tmp.si]) { pw.println((tmp.fi+1)+" "+(tmp.si+1)); visited[tmp.fi]=true; visited[tmp.si]=true; int left=l[tmp.fi]; int right=r[tmp.si]; if(right<n) // WE HAVE DONE THIS TO MAKE CONNECTIONS //6 //BBGBGG //6 4 3 7 5 1 IF WE REMOVE THESE CONNECTIONS THEN THIS ANSWER WILL BE WRONG l[right]=left; if(left>=0) r[left]=right; if(left>=0 && right<n && str.charAt(left)!=str.charAt(right)) { pq.add(new Node(left,right,Math.abs(ar[left]-ar[right]))); } } } pw.close(); } } class Node{ int fi; int si; int ti; public Node(int fi,int si,int ti) { this.fi=fi; this.si=si; this.ti=ti; } }
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; vector<pair<int, pair<int, int> > > heap; vector<pair<int, int> > ans; int N, a[1000009], n[1000009], p[10000009], u[10000009]; char g[10000009]; int fn(int first) { if (u[n[first]]) n[first] = fn(n[first]); return n[first]; } int fp(int first) { if (u[p[first]]) p[first] = fp(p[first]); return p[first]; } int main() { scanf("%d%s", &N, g); for (int i = 0; i < N; i++) { scanf("%d", &a[i]); p[i] = i - 1; n[i] = i + 1; } for (int i = 1; i < N; i++) if (g[i] != g[i - 1]) heap.push_back(make_pair( ((a[i] - a[i - 1]) < 0 ? (a[i] - a[i - 1]) : -(a[i] - a[i - 1])), make_pair(-i + 1, -i))); make_heap(heap.begin(), heap.end()); while (heap.size()) { int A, B; A = -heap.begin()->second.second; B = -heap.begin()->second.first; pop_heap(heap.begin(), heap.end()); heap.pop_back(); if (u[A] || u[B]) continue; u[A] = u[B] = 1; ans.push_back(make_pair(A, B)); A = fp(A); B = fn(B); if (A != -1 && B != N) if (g[A] != g[B]) { heap.push_back( make_pair(((a[A] - a[B]) < 0 ? (a[A] - a[B]) : -(a[A] - a[B])), make_pair(-A, -B))); push_heap(heap.begin(), heap.end()); } } printf("%d\n", ans.size()); for (int i = 0; i < ans.size(); i++) printf("%d %d\n", ans[i].second + 1, ans[i].first + 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,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') # Made By Mostafa_Khaled
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 n = int(input()) gender = [char for char in input()] a = [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 gender[i] != gender[i - 1]: heapq.heappush(difference,(abs(a[i] - a[i - 1]),i - 1,i)) while len(difference): dif,fir,sec = heapq.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 gender[r] != gender[s]: heapq.heappush(difference,(abs(a[r] - a[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; const int MAXn = 2 * 100000 + 100; int n; char s[MAXn]; int a[MAXn]; int prv[MAXn], nxt[MAXn]; bool gone[MAXn]; struct couple { int left, right; couple(int left, int right) : left(left), right(right) {} bool operator<(couple X) const { return abs(a[left] - a[right]) == abs(a[X.left] - a[X.right]) ? left > X.left : abs(a[left] - a[right]) > abs(a[X.left] - a[X.right]); } }; priority_queue<couple> pq; int main() { cin >> n; cin >> s; for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) prv[i] = i - 1, nxt[i] = i + 1; int cnt = 0; for (int i = 0; i < n; i++) cnt += (s[i] == 'B'); cout << min(cnt, n - cnt) << endl; for (int i = 0; i < n - 1; i++) if (s[i] != s[i + 1]) pq.push(couple(i, i + 1)); while (!pq.empty()) { int l = pq.top().left, r = pq.top().right; pq.pop(); if (gone[l] || gone[r]) continue; gone[l] = gone[r] = true; cout << l + 1 << ' ' << r + 1 << endl; l = prv[l], r = nxt[r]; if (l != -1) nxt[l] = r; if (r != n) prv[r] = l; if (l != -1 && r != n && s[l] != s[r]) pq.push(couple(l, r)); } { int _; cin >> _; } }
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> const long long inf = 1e9 + 44; const int MAX = 3e5 + 9; const long long MOD = 1e9 + 7; const double eps = 1e-10; double const PI = 3.1415926535897931; using namespace std; int dx[4] = {1, 0, -1, 0}; int dy[4] = {0, 1, 0, -1}; void _print(vector<int> v) { cout << "[ "; for (auto u : v) cout << u << " "; cout << " ]" << endl; } int main() { int n; cin >> n; string s; cin >> s; set<pair<int, pair<int, int> > > st; int arr[n + 6], l[n + 1], r[n + 1]; set<int> t; for (int i = 0; i < n; i++) { cin >> arr[i]; t.insert(i); } for (int i = 1; i < n; i++) { if (s[i] != s[i - 1]) { st.insert({abs(arr[i] - arr[i - 1]), {i, i - 1}}); } } int vis[n + 1]; memset(vis, 0, sizeof(vis)); vector<pair<int, int> > ans; while (st.size()) { pair<int, pair<int, int> > now = *st.begin(); st.erase(st.begin()); int u = now.second.first; int v = now.second.second; if (t.find(u) == t.end() || t.find(v) == t.end()) continue; ans.push_back(now.second); t.erase(u); t.erase(v); auto it = t.lower_bound(v); if (it != t.end()) { auto it1 = it; if (it != t.begin()) it--; if (s[*it] != s[*it1]) st.insert({abs(arr[*it] - arr[*it1]), {*it1, *it}}); } } cout << ans.size() << endl; for (int i = 0; i < ans.size(); i++) cout << ans[i].second + 1 << " " << ans[i].first + 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 MAXN = 2 * 110000; int a[MAXN]; int L[MAXN], R[MAXN]; char C[MAXN]; bool was[MAXN]; struct Pair { int id1; int id2; Pair(int id1 = 0, int id2 = 0) { this->id1 = id1; this->id2 = id2; } bool operator<(const Pair& p) const { if (abs(a[id1] - a[id2]) != abs(a[p.id1] - a[p.id2])) return abs(a[id1] - a[id2]) < abs(a[p.id1] - a[p.id2]); if (id1 ^ p.id1) return id1 < p.id1; return id2 < p.id2; } }; set<Pair> Set; int n; int main() { scanf("%d\n", &n); gets(C); for (int i = 0; i < n; ++i) scanf("%d", &a[i]); for (int i = 0; i < n - 1; ++i) { L[i] = i - 1; R[i] = i + 1; if ((C[i] == 'B') != (C[i + 1] == 'B')) { Set.insert(Pair(i, i + 1)); } } L[n - 1] = n - 2; R[n - 1] = -1; vector<Pair> res; while (!Set.empty()) { Pair cur = *Set.begin(); Set.erase(Set.begin()); if (was[cur.id1] || was[cur.id2]) continue; was[cur.id1] = true; was[cur.id2] = true; res.push_back(cur); int x = -1, y = -1; if (L[cur.id1] != -1) { y = R[L[cur.id1]] = R[cur.id2]; } if (R[cur.id2] != -1) { x = L[R[cur.id2]] = L[cur.id1]; } if (x != -1 && y != -1) { if ((C[x] == 'B') != (C[y] == 'B')) { Set.insert(Pair(x, y)); } } } printf("%d\n", res.size()); for (int i = 0; i < (int)res.size(); ++i) printf("%d %d\n", res[i].id1 + 1, res[i].id2 + 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; using namespace std; const int MAXN = 2e5 + 5; int a[MAXN]; char s[MAXN]; int l[MAXN], r[MAXN]; vector<pair<int, int> > v; bool vis[MAXN]; int main() { int m, n, i, j, k; scanf("%d", &m); for (i = 1; i <= m; i++) l[i] = i - 1, r[i] = i + 1, vis[i] = 1; scanf("%s", s + 1); for (i = 1; i <= m; i++) scanf("%d", &a[i]); set<pair<int, pair<int, int> > > ss; set<pair<int, pair<int, int> > >::iterator it; for (i = 2; i <= m; i++) { if (s[i] != s[i - 1]) { ss.insert({abs(a[i] - a[i - 1]), {i - 1, i}}); } } while (ss.size()) { it = ss.begin(); pair<int, pair<int, int> > p = *it; ss.erase(it); int i = p.second.first, j = p.second.second; if (vis[i] && vis[j]) { v.push_back({i, j}); vis[i] = vis[j] = false; i = l[i]; j = r[j]; r[i] = j; l[j] = i; if (vis[i] && vis[j] && s[i] != s[j]) { ss.insert({abs(a[i] - a[j]), {i, j}}); } } } cout << v.size() << endl; for (i = 0; i < v.size(); i++) printf("%d %d\n", v[i].first, v[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.util.*; import java.io.*; public class helloworld { static long fact[]; static long max; static int ans; static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static long getSum(int index , long BITree[]) { long sum = 0; // Iniialize result // index in BITree[] is 1 more than // the index in arr[] // Traverse ancestors of BITree[index] while(index>0) { // Add current element of BITree // to sum sum += BITree[index]; // Move index to parent node in // getSum View index -= index & (-index); } return sum; } static int getMid(int s, int e) { return s + (e - s) / 2; } /* * A recursive function to get the sum of values in given range of the array. * The following are parameters for this function. * * st -> Pointer to segment tree * node -> Index of current node in * the segment tree. * ss & se -> Starting and ending indexes * of the segment represented * by current node, i.e., st[node] * l & r -> Starting and ending indexes * of range query */ static int MaxUtil(int[] st, int ss, int se, int l, int r, int node) { // If segment of this node is completely // part of given range, then return // the max of segment if (l <= ss && r >= se) return st[node]; // If segment of this node does not // belong to given range if (se < l || ss > r) return -1; // If segment of this node is partially // the part of given range int mid = getMid(ss, se); return Math.max(MaxUtil(st, ss, mid, l, r, 2 * node + 1), MaxUtil(st, mid + 1, se, l, r, 2 * node + 2)); } /* * A recursive function to update the nodes which have the given index in their * range. The following are parameters st, ss and se are same as defined above * index -> index of the element to be updated. */ static void updateValue(int arr[], int[] st, int ss, int se, int index, int value, int node) { if (index < ss || index > se) { System.out.println("Invalid Input"); return; } if (ss == se) { // update value in array and in segment tree arr[index] = value; st[node] = value; } else { int mid = getMid(ss, se); if (index >= ss && index <= mid) updateValue(arr, st, ss, mid, index, value, 2 * node + 1); else updateValue(arr, st, mid + 1, se, index, value, 2 * node + 2); st[node] = Math.max(st[2 * node + 1], st[2 * node + 2]); } return; } // Return max of elements in range from // index l (query start) to r (query end). static int getMax(int[] st, int n, int l, int r) { // Check for erroneous input values if (l < 0 || r > n - 1 || l > r) { System.out.printf("Invalid Input\n"); return -1; } return MaxUtil(st, 0, n - 1, l, r, 0); } // A recursive function that constructs Segment // Tree for array[ss..se]. si is index of // current node in segment tree st static int constructSTUtil(int arr[], int ss, int se, int[] st, int si) { // If there is one element in array, store // it in current node of segment tree and return if (ss == se) { st[si] = arr[ss]; return arr[ss]; } // If there are more than one elements, then // recur for left and right subtrees and // store the max of values in this node int mid = getMid(ss, se); st[si] = Math.max(constructSTUtil(arr, ss, mid, st, si * 2 + 1), constructSTUtil(arr, mid + 1, se, st, si * 2 + 2)); return st[si]; } /* * Function to construct segment tree from given array. This function allocates * memory for segment tree. */ static int[] constructST(int arr[], int n) { // Height of segment tree int x = (int) Math.ceil(Math.log(n) / Math.log(2)); // Maximum size of segment tree int max_size = 2 * (int) Math.pow(2, x) - 1; // Allocate memory int[] st = new int[max_size]; // Fill the allocated memory st constructSTUtil(arr, 0, n - 1, st, 0); // Return the constructed segment tree return st; } public static void updateBIT(int n, int index, long val , long BITree[] ) { // index in BITree[] is 1 more than // the index in arr[] // Traverse all ancestors and add 'val' while(index <= n) { // Add 'val' to current node of BIT Tree BITree[index] += val; // Update index to that of parent // in update View index += index & (-index); } } static long mod = 1000000007; static long pow(long a , long b , long c) { if(b==0) return 1; long ans = pow(a,b/2,c); if(b%2 == 0) return ans*ans%c; return ans*ans%c*a%c; } static long modInverse(long a , long b) { return pow(a,b-2,mod); } static double d(int x1 , int y1 , int x2 , int y2) { double d1 = x1-x2; double d2 = y1-y2; return Math.sqrt(d1*d1-d2*d2); } static int low[]; static int p[]; static int parent(int x , int k , int dp[][]) { if(k==0) return x; while(k > 0) { if(x == -1) break; int up = low[k]; k -= p[up]; x = dp[x][up]; } return x; } static void d(int n , LinkedList<Integer> arr[] , boolean visited[] , int dp[][] , int h[] , int p,int lev) { visited[n] = true; int lim = low[visited.length]; dp[n][0] = p; int temp = n; for(int j = 1 ; j <= lim ; j++) { if(dp[n][j-1] == -1) break; dp[n][j] = dp[dp[n][j-1]][j-1]; } h[n] = lev; for(Integer i : arr[n]) { if(!visited[i]) { d(i,arr,visited,dp,h,n,lev+1); } } } static int lca(int a , int b , int dp[][] , int h[]) { if(h[a] > h[b]) { a = parent(a,h[a]-h[b],dp); } else if(h[b] > h[a]) { b = parent(b,h[b]-h[a],dp); } if(a==b) return a; int l = 1 , r = h.length; while(l < r) { int mid = (l+r)/2; if(parent(a,mid,dp) == parent(b,mid,dp)) r = mid; else l = mid+1; } return parent(a,l,dp); } static void dfs(int n , LinkedList<Integer> arr[] , boolean visited[] , int dp[] , int idx[] , int ans[]) { visited[n] = true; for(Integer i : arr[n]) { if(!visited[i]) { dfs(i,arr,visited,dp,idx,ans); dp[n] += dp[i]; } } if(n != 1) ans[idx[n]] = dp[n]; //System.out.println(dp[n] + " " + idx[n]); } public static void main(String []args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); sc.nextLine(); String s = sc.nextLine(); int arr[] = new int[n]; for(int i = 0 ; i < n ; i++) { arr[i] = sc.nextInt(); } TreeMap<Integer,Integer> point = new TreeMap<Integer,Integer>(); TreeMap<pair,Integer> map = new TreeMap<pair,Integer>(new Compare()); int cnt = 0; StringBuffer str = new StringBuffer(""); for(int i = 0 ; i < n-1 ; i++) { if(s.charAt(i) != s.charAt(i+1)) { map.put(new pair(Math.abs(arr[i]-arr[i+1]),i+1,i+2), 1); } point.put(i+1,1); } point.put(n,1); while(map.size() > 0) { pair pp = map.firstKey(); cnt++; str.append(pp.idx + " " + (pp.idx2)); str.append(System.getProperty("line.separator")); map.remove(pp); if(point.lowerKey(pp.idx) != null) { int idx = point.lowerKey(pp.idx); if(s.charAt(idx-1) != s.charAt(pp.idx-1)) map.remove(new pair(Math.abs(arr[idx-1]-arr[pp.idx-1]),idx,pp.idx)); } if(point.higherKey(pp.idx2) != null) { int idx = point.higherKey(pp.idx2); if(s.charAt(pp.idx2-1) != s.charAt(idx-1)) map.remove(new pair(Math.abs(arr[idx-1]-arr[pp.idx2-1]) , pp.idx2 , idx)); } if(point.lowerKey(pp.idx) != null && point.higherKey(pp.idx2) != null) { int idx1 = point.lowerKey(pp.idx); int idx2 = point.higherKey(pp.idx2); if(s.charAt(idx1-1) != s.charAt(idx2-1)) { map.put(new pair(Math.abs(arr[idx1-1] - arr[idx2-1]) , idx1 , idx2), 1); } } point.remove(pp.idx); point.remove(pp.idx2); } System.out.println(cnt); System.out.println(str); } } class pair { int diff , idx , idx2; public pair(int diff , int idx , int idx2) { this.diff = diff; this.idx = idx; this.idx2 = idx2; } } class Compare implements Comparator<pair> { public int compare(pair a , pair b) { if(a.diff != b.diff) return a.diff - b.diff; return a.idx-b.idx; } }
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; int main() { priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, greater<pair<int, pair<int, int>>>> q; int n; unordered_set<int> s; set<int> unseen; cin >> n; string str; cin >> str; vector<int> arr(n); for (int i = 0; i < n; i++) { cin >> arr[i]; unseen.insert(i); } for (int i = 0; i < str.length() - 1; i++) { if (str[i] != str[i + 1]) q.push(make_pair(abs(arr[i] - arr[i + 1]), make_pair(i, i + 1))); } vector<pair<int, int>> res; while (!q.empty()) { pair<int, pair<int, int>> curr = q.top(); q.pop(); if (s.find(curr.second.first) != s.end() || s.find(curr.second.second) != s.end()) continue; s.insert(curr.second.first); s.insert(curr.second.second); res.push_back(curr.second); int i = curr.second.first; int j = curr.second.second; auto prevI = unseen.lower_bound(i); auto nextJ = unseen.upper_bound(j); if (prevI == unseen.begin() || nextJ == unseen.end()) { unseen.erase(i); unseen.erase(j); continue; } int pi = *(--prevI); int nj = *nextJ; if (str[pi] != str[nj]) { q.push(make_pair(abs(arr[pi] - arr[nj]), make_pair(pi, nj))); } unseen.erase(i); unseen.erase(j); } cout << res.size() << endl; for (int i = 0; i < res.size(); i++) { cout << res[i].first + 1 << " " << res[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; int n; char s[200005]; int v[200005]; struct node { int l, r, v; void init(int ll, int rr, int vv) { l = ll; r = rr; v = vv; } friend bool operator<(const node& a, const node& b) { if (a.v != b.v) return a.v > b.v; return a.l > b.l; } } n1; priority_queue<node> qu; int L[200005], R[200005]; bool used[200005]; int x[100005], y[100005], len; int main() { scanf("%d%s", &n, s + 1); int i; for (i = 1; i <= n; i++) scanf("%d", v + i); for (i = 1; i <= n; i++) L[i] = i - 1, R[i] = i + 1; for (i = 2; s[i]; i++) { if (s[i] != s[i - 1]) { n1.init(i - 1, i, abs(v[i] - v[i - 1])); qu.push(n1); } } while (!qu.empty()) { n1 = qu.top(); qu.pop(); if (used[n1.l] || used[n1.r]) continue; used[n1.l] = used[n1.r] = 1; x[len] = n1.l; y[len++] = n1.r; int a = L[n1.l], b = R[n1.r]; if (a > 0 && b <= n) { R[L[n1.l]] = R[n1.r]; L[R[n1.r]] = L[n1.l]; if (s[a] != s[b]) { n1.init(a, b, abs(v[a] - v[b])); qu.push(n1); } } } printf("%d\n", len); for (i = 0; i < len; i++) { printf("%d %d\n", x[i], y[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
#include <bits/stdc++.h> struct Node { int l, r, s; }; struct Pair { int p1, p2, d; Pair(int p1, int p2, int d) : p1(p1), p2(p2), d(d) {} bool operator>(const Pair& rhs) const { return d > rhs.d || (!(rhs.d > d) && p1 > rhs.p1); } }; int main() { int n; std::string s; std::cin >> n >> s; std::vector<Node> v(n); for (int i = 0; i < n; ++i) { scanf("%d", &v[i].s); v[i].l = i - 1; v[i].r = i + 1; } std::priority_queue<Pair, std::vector<Pair>, std::greater<Pair> > q; for (int i = 0; i < n - 1; ++i) { if (s[i] != s[i + 1]) { q.push(Pair(i, i + 1, abs(v[i].s - v[i + 1].s))); } } std::vector<int> used(n); std::vector<std::pair<int, int> > res; while (!q.empty()) { Pair top = q.top(); q.pop(); int p1 = top.p1; int p2 = top.p2; if (used[p1] || used[p2]) { continue; } used[p1] = used[p2] = 1; res.push_back(std::make_pair(p1, p2)); Node& u = v[p1]; Node& w = v[p2]; if (0 <= u.l) { v[u.l].r = w.r; } if (w.r < n) { v[w.r].l = u.l; } if (0 <= u.l && w.r < n && s[u.l] != s[w.r]) { q.push(Pair(u.l, w.r, abs(v[u.l].s - v[w.r].s))); } } std::cout << res.size() << std::endl; for (int i = 0; i < (int)res.size(); ++i) { std::cout << res[i].first + 1 << " " << res[i].second + 1 << std::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
// Don't place your source in a package import javax.swing.*; import java.lang.reflect.Array; import java.text.DecimalFormat; import java.util.*; import java.lang.*; import java.io.*; import java.math.*; import java.util.stream.Stream; // Please name your class Main public class Main { static FastScanner fs=new FastScanner(); static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int Int() { return Integer.parseInt(next()); } long Long() { return Long.parseLong(next()); } String Str(){ return next(); } } public static void main (String[] args) throws java.lang.Exception { PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int T=1; for(int t=0;t<T;t++){ int n=Int(); String s=Str(); int A[][]=new int[n][2]; for(int i=0;i<n;i++){ A[i][0]=Int(); if(s.charAt(i)=='B')A[i][1]=1; } Solution sol=new Solution(out); sol.solution(A); } out.close(); } public static int[] Arr(int n){ int A[]=new int[n]; for(int i=0;i<n;i++)A[i]=Int(); return A; } public static int Int(){ return fs.Int(); } public static long Long(){ return fs.Long(); } public static String Str(){ return fs.Str(); } } class Solution{ PrintWriter out; public Solution(PrintWriter out){ this.out=out; } public void solution(int A[][]){ //0:girl 1:boy TreeSet<Integer>tree=new TreeSet<>(); for(int i=0;i<A.length;i++){ tree.add(i); } PriorityQueue<int[]>pq=new PriorityQueue<>((a,b)->{ if(a[0]==b[0]){//same return a[1]-b[1]; } else{ return a[0]-b[0]; } }); for(int i=1;i<A.length;i++){ int dif=Math.abs(A[i][0]-A[i-1][0]); int pair[]=new int[]{dif,i-1,i}; pq.add(pair); } List<int[]>res=new ArrayList<>(); while(pq.size()>0){ int top[]=pq.poll(); int l=top[1],r=top[2]; if(!tree.contains(l)||!tree.contains(r))continue; if(A[l][1]==A[r][1])continue; tree.remove(l);tree.remove(r); res.add(new int[]{l,r}); Integer floor=tree.floor(l); Integer ceil=tree.ceiling(r); if(floor!=null&&ceil!=null){ int dif=Math.abs(A[ceil][0]-A[floor][0]); pq.add(new int[]{dif,floor,ceil}); } } out.println(res.size()); for(int p[]:res){ out.println((p[0]+1)+" "+(p[1]+1)); } } } /* ;\ |' \ _ ; : ; / `-. /: : | | ,-.`-. ,': : | \ : `. `. ,'-. : | \ ; ; `-.__,' `-.| \ ; ; ::: ,::'`:. `. \ `-. : ` :. `. \ \ \ , ; ,: (\ \ :., :. ,'o)): ` `-. ,/,' ;' ,::"'`.`---' `. `-._ ,/ : ; '" `;' ,--`. ;/ :; ; ,:' ( ,:) ,.,:. ; ,:., ,-._ `. \""'/ '::' `:'` ,'( \`._____.-'"' ;, ; `. `. `._`-. \\ ;:. ;: `-._`-.\ \`. '`:. : |' `. `\ ) \ -hrr- ` ;: | `--\__,' '` ,' ,-' free bug dog */
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 man { int l, r; }; bool U[200010]; man sosed[200010]; int skill[200010]; char sex[200010]; int main() { int n; cin >> n; priority_queue<pair<int, int> > Q; for (int i = 0; i < n; ++i) { cin >> sex[i]; } for (int i = 0; i < n; ++i) { cin >> skill[i]; } for (int i = 0; i < n; ++i) { if (i > 0) if (sex[i] != sex[i - 1]) Q.push(make_pair(-abs(skill[i] - skill[i - 1]), -(i - 1))); sosed[i].l = i - 1; sosed[i].r = i + 1; } vector<pair<int, int> > res; pair<int, int> v; int f, s; while (!Q.empty()) { v = Q.top(); Q.pop(); f = -v.second; s = sosed[f].r; if (f >= 0 && s < n && !U[f] && !U[s]) if (abs(skill[f] - skill[s]) == -v.first && sex[f] != sex[s]) { res.push_back(make_pair(f + 1, s + 1)); U[f] = true; U[s] = true; sosed[sosed[f].l].r = sosed[s].r; sosed[sosed[s].r].l = sosed[f].l; if (sosed[f].l >= 0 && sosed[s].r < n && sex[sosed[f].l] != sex[sosed[s].r]) Q.push(make_pair(-abs(skill[sosed[f].l] - skill[sosed[s].r]), -(sosed[f].l))); } } cout << res.size() << endl; for (int i = 0; i < res.size(); ++i) cout << res[i].first << " " << res[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; const int maxn = 250000; bool vis[maxn]; int sk[maxn]; int ll[maxn], rr[maxn]; char s[maxn]; int n; struct node { int u, v, val; }; bool operator<(const node a, const node b) { if (a.val != b.val) return a.val > b.val; return a.u > b.u; } priority_queue<node> q; int main() { while (cin >> n) { node tmp; int num = 0; scanf("%s", s + 1); for (int i = 1; i <= n; i++) { ll[i] = i - 1; rr[i] = i + 1; if (s[i] == 'B') num += 1; } num = (num < n - num) ? num : n - num; for (int i = 1; i <= n; i++) scanf("%d", &sk[i]); while (!q.empty()) q.pop(); for (int i = 1; i < n; i++) { if (s[i] != s[i + 1]) { tmp.u = i; tmp.v = i + 1; tmp.val = abs(sk[i] - sk[i + 1]); q.push(tmp); } } memset(vis, 0, sizeof vis); printf("%d\n", num); while (num--) { while (!q.empty()) { tmp = q.top(); q.pop(); if (!vis[tmp.u] && !vis[tmp.v]) { printf("%d %d\n", tmp.u, tmp.v); vis[tmp.u] = 1; vis[tmp.v] = 1; break; } } int a = ll[tmp.u]; int b = rr[tmp.v]; rr[a] = b; ll[b] = a; tmp.u = a; tmp.v = b; tmp.val = abs(sk[a] - sk[b]); if (a > 0 && b <= n && s[a] != s[b]) q.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; struct Node { int val; int left, right; }; struct cmp { bool operator()(const Node& lhs, const Node& rhs) { if (lhs.val != rhs.val) { return lhs.val > rhs.val; } else { return lhs.left > rhs.left; } } }; int main() { ios::sync_with_stdio(0); cin.tie(0); int n; cin >> n; string gender; cin >> gender; vector<Node> a(n); vector<bool> visited(n, false); priority_queue<Node, vector<Node>, cmp> pq; for (int i = (0); i < (n); ++i) { cin >> a[i].val; if (i > 0) { a[i].left = i - 1; if (gender[i - 1] != gender[i]) { pq.push({abs(a[i].val - a[i - 1].val), i - 1, i}); } } else { a[i].left = -1; } if (i < n - 1) { a[i].right = i + 1; } else { a[i].right = -1; } } vector<pair<int, int> > ans; while (!pq.empty()) { Node top = pq.top(); pq.pop(); int x = top.left; int y = top.right; if (visited[x] || visited[y]) continue; visited[x] = visited[y] = true; ans.push_back({x + 1, y + 1}); if (a[x].left != -1) { a[a[x].left].right = a[y].right; } if (a[y].right != -1) { a[a[y].right].left = a[x].left; } if (a[x].left != -1 && a[y].right != -1 && gender[a[x].left] != gender[a[y].right]) { pq.push( {abs(a[a[x].left].val - a[a[y].right].val), a[x].left, a[y].right}); } } cout << ans.size() << "\n"; for (pair<int, int>& a : ans) { cout << a.first << " " << a.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; #pragma GCC diagnostic warning "-Wall" int main() { ios::sync_with_stdio(false); int n; string sex; cin >> n; cin >> sex; vector<int> skill(n); for (typeof(n) i = (0); i < (n); i++) cin >> skill[i]; vector<int> prev(n); prev[0] = -1; for (typeof(n) i = (1); i < (n); i++) prev[i] = i - 1; vector<int> next(n); next[n - 1] = -1; for (typeof(n - 1) i = (0); i < (n - 1); i++) next[i] = i + 1; set<pair<int, pair<int, int> > > q; for (typeof(n - 1) ia = (0); ia < (n - 1); ia++) { int ib = ia + 1; if (sex[ia] == sex[ib]) continue; q.insert(make_pair(abs(skill[ia] - skill[ib]), make_pair(ia, ib))); } vector<bool> used(n); vector<pair<int, int> > couples; while (not q.empty()) { pair<int, int> c = q.begin()->second; q.erase(q.begin()); if (used[c.first] or used[c.second]) continue; couples.push_back(c); used[c.first] = true; used[c.second] = true; if (prev[c.first] != -1) next[prev[c.first]] = next[c.second]; if (next[c.second] != -1) prev[next[c.second]] = prev[c.first]; if (prev[c.first] != -1 and next[c.second] != -1) { int ia = prev[c.first]; int ib = next[c.second]; if (sex[ia] != sex[ib]) { q.insert(make_pair(abs(skill[ia] - skill[ib]), make_pair(ia, ib))); } } } cout << couples.size() << endl; for (typeof((couples).begin()) c = (couples).begin(); c != (couples).end(); c++) { cout << (c->first + 1) << " " << (c->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 Event { int d, a, b; Event(int _d, int _a, int _b) : d(_d), a(_a), b(_b) {} bool operator<(const Event &x) const { if (d != x.d) return d > x.d; return min(a, b) > min(x.a, x.b); } }; const int MN = 200009; char T[MN]; int D[MN]; set<int> K; vector<pair<int, int> > Out; int main() { priority_queue<Event> Q; int n; scanf("%d", &n); scanf("%s", T); for (int i = (0); i < (n); ++i) { scanf("%d", &D[i]); K.insert(i); } for (int i = (0); i < (n - 1); ++i) if (T[i] != T[i + 1]) Q.push(Event(abs(D[i] - D[i + 1]), i, i + 1)); while (!Q.empty()) { Event e = Q.top(); Q.pop(); set<int>::iterator at = K.find(e.a), bt = K.find(e.b), att, btt; if (at != K.end() && bt != K.end()) { Out.push_back(make_pair(min(e.a, e.b), max(e.a, e.b))); att = at; btt = bt; btt++; if (at != K.begin() && btt != K.end()) { att--; if (T[*att] != T[*btt]) Q.push(Event(abs(D[*att] - D[*btt]), *att, *btt)); } K.erase(at); K.erase(bt); } } printf("%d\n", Out.size()); for (__typeof__((Out).begin()) w = (Out).begin(); w != (Out).end(); ++w) printf("%d %d\n", w->first + 1, w->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
#include <bits/stdc++.h> using namespace std; const int M = 1000000; int n; char s[M]; int xs[M]; bool used[M]; struct S { int l, r; S() {} S(int a, int b) : l(a), r(b) {} bool operator<(const S& s) const { const int a = abs(xs[l] - xs[r]), b = abs(xs[s.l] - xs[s.r]); return a > b || a == b && l > s.l; } }; S ys[M]; int main() { scanf("%d", &n); scanf("%s", s); int i, b = 0, g = 0; for (i = (int)0; i < (int)n; i++) { scanf("%d", &xs[i]); ys[i].l = i - 1; ys[i].r = i + 1; if (s[i] == 'B') b++; else g++; } priority_queue<S> q; for (i = (int)0; i < (int)n - 1; i++) if (s[i] != s[i + 1]) q.push(S(i, i + 1)); int times = min(b, g); vector<S> res; while (!q.empty()) { S t = q.top(); q.pop(); if (used[t.l] || used[t.r]) continue; res.push_back(t); if (--times == 0) break; used[t.l] = used[t.r] = true; if (ys[t.l].l >= 0) ys[ys[t.l].l].r = ys[t.r].r; if (ys[t.r].r < n) ys[ys[t.r].r].l = ys[t.l].l; t.l = ys[t.l].l; t.r = ys[t.r].r; if (0 <= t.l && t.r < n && s[t.l] != s[t.r]) { q.push(S(t.l, t.r)); } } printf("%d\n", (int)res.size()); for (i = (int)0; i < (int)res.size(); i++) { printf("%d %d\n", res[i].l + 1, res[i].r + 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 double pi = acos(-1.0); const double eps = 1e-9; const long long INF = 100000000000000000; const int MAXN = 3 * 100000; struct T { int left, right, diff; bool operator>(const T& other) { if (diff != other.diff) return diff < other.diff; return left < other.left; } bool operator<(const T& other) const { if (diff != other.diff) return diff > other.diff; return left > other.left; } }; priority_queue<T> q; vector<pair<int, int> > ans; char s[MAXN]; bool u[MAXN]; int a[MAXN]; int l[MAXN]; int r[MAXN]; int n; int main() { cin >> n; scanf("%s", s); for (int i = 0; i < n; ++i) { scanf("%d", &a[i]); l[i] = i - 1; r[i] = i + 1; if (i + 1 == n) r[i] = -1; } for (int i = 0; i < n - 1; ++i) if (s[i] != s[i + 1]) { T t; t.left = i; t.right = i + 1; t.diff = abs(a[i] - a[i + 1]); q.push(t); } while (!q.empty()) { int left = q.top().left; int right = q.top().right; q.pop(); if (u[left] || u[right]) continue; u[left] = u[right] = true; ans.push_back(pair<int, int>(left + 1, right + 1)); left = l[left]; right = r[right]; if (left != -1) r[left] = right; if (right != -1) l[right] = left; if (left != -1 && right != -1 && s[left] != s[right]) { T t; t.left = left; t.right = right; t.diff = abs(a[left] - a[right]); q.push(t); } } cout << ans.size() << endl; for (int i = 0; i < (long long)(ans).size(); ++i) { printf("%d %d\n", ans[i].first, 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
#include <bits/stdc++.h> using namespace std; struct thing { int L; int R; int V; bool operator<(const thing &th) const { if (V > th.V || (V == th.V && L > th.L)) return true; return false; } } in; priority_queue<thing> work; int N, give; bool b[200010]; int v[200010]; bool ed[200010]; int L[200010]; int R[200010]; int main() { cin >> N; getchar(); for (int i = 1; i <= N; i++) if (getchar() == 'B') { b[i] = true; give++; } give = min(give, N - give); cout << give << endl; for (int i = 1; i <= N; i++) scanf("%d", &v[i]); for (int i = 1; i <= N; i++) { L[i] = i - 1; R[i] = i + 1; } for (int i = 1; i < N; i++) { if (b[i] == b[i + 1]) continue; in.L = i; in.R = i + 1; in.V = abs(v[i] - v[i + 1]); work.push(in); } while (give--) { in = work.top(); work.pop(); while (ed[in.L] || ed[in.R]) { in = work.top(); work.pop(); } printf("%d %d\n", in.L, in.R); ed[in.L] = true; ed[in.R] = true; L[R[in.R]] = L[in.L]; R[L[in.L]] = R[in.R]; if (L[in.L] >= 1 && R[in.R] <= N && b[L[in.L]] != b[R[in.R]]) { in.L = L[in.L]; in.R = R[in.R]; in.V = abs(v[in.L] - v[in.R]); work.push(in); } } 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> struct BG { int diff; int pos; int second; BG() {} BG(int diff, int pos, int second) : diff(diff), pos(pos), second(second) {} bool operator<(BG const& p) const { if (diff != p.diff) return diff > p.diff; return pos > p.pos; } }; struct Using { int n; std::vector<int> next; std::vector<int> prev; Using() {} Using(int n) : n(n) { next.resize(n); for (int i = 0; i < n; ++i) next[i] = i; prev.resize(n); for (int i = 0; i < n; ++i) prev[i] = i; } void use(int i) { if (!used(i)) { next[i] = i + 1; prev[i] = i - 1; } } int get_next(int i) { if (i == n) return n; if (next[i] != i) { next[i] = get_next(next[i]); } return next[i]; } int get_prev(int i) { if (i == -1) return -1; if (prev[i] != i) { prev[i] = get_prev(prev[i]); } return prev[i]; } bool used(int i) { return next[i] != i; } }; int const N = 200100; char s[N]; int a[N]; int main() { int n; scanf("%d", &n); Using poses(n); scanf("%s", s); for (int i = 0; i < n; ++i) scanf("%d", a + i); std::priority_queue<BG> pairs; for (int i = 0; i + 1 < n; ++i) { if (s[i] != s[i + 1]) { pairs.push(BG(std::abs(a[i] - a[i + 1]), i, i + 1)); } } std::vector<BG> ans; while (!pairs.empty()) { BG p = pairs.top(); pairs.pop(); if (poses.used(p.pos) || poses.used(p.second)) continue; ans.push_back(p); poses.use(p.pos); poses.use(p.second); int i = poses.get_prev(p.pos); int j = poses.get_next(p.second); if (i != -1 && j != n && s[i] != s[j]) { pairs.push(BG(std::abs(a[i] - a[j]), i, j)); } } printf("%d\n", (int)ans.size()); for (BG p : ans) { printf("%d %d\n", p.pos + 1, p.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
#include <bits/stdc++.h> using namespace std; int skil[200007], pre[200007], post[200007]; bool flag[200007]; char s[200007]; struct data { int l, r; data() {} data(int a, int b) { l = a; r = b; } bool operator<(const data& a) const { return abs(skil[l] - skil[r]) == abs(skil[a.l] - skil[a.r]) ? (l > a.l) : abs(skil[l] - skil[r]) > abs(skil[a.l] - skil[a.r]); } }; int main() { int n, i, b, g; priority_queue<data> pq; scanf("%d", &n); getchar(); scanf("%s", &s[1]); s[0] = s[1]; s[n + 1] = s[n]; for (i = 1, b = g = 0; i <= n; i++) { scanf("%d", &skil[i]); pre[i] = i - 1; post[i] = i + 1; if (s[i] == 'B') b++; else g++; if (s[i] ^ s[i - 1]) { pq.push(data(i - 1, i)); } } printf("%d\n", min(b, g)); flag[0] = flag[n + 1] = true; while (!pq.empty()) { data u = pq.top(); pq.pop(); if (flag[u.l] || flag[u.r]) continue; printf("%d %d\n", u.l, u.r); flag[u.l] = flag[u.r] = true; post[pre[u.l]] = post[u.r]; pre[post[u.r]] = pre[u.l]; if (!flag[pre[u.l]] && !flag[post[u.r]]) { if (s[pre[u.l]] ^ s[post[u.r]]) { pq.push(data(pre[u.l], post[u.r])); } } } 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 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]] #print(line) 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; vector<int> v; struct po { int diff; int l; int r; bool operator()(const po& l, const po& r) { if (l.diff == r.diff) { if (l.l == r.l) return l.r > r.r; return l.l > r.l; } return l.diff > r.diff; } }; vector<po> ans; int vis[200005]; set<int> pos; priority_queue<po, vector<po>, po> pq; int main() { int n; int x; cin >> n; string s; cin >> s; po p; for (int i = 0; i < n; i++) { cin >> x; v.push_back(x); pos.insert(i + 1); } pos.insert(0); pos.insert(n + 1); for (int i = 0; i < n - 1; i++) { if (s[i] != s[i + 1]) { p.diff = abs(v[i] - v[i + 1]); p.l = i + 1; p.r = i + 2; pq.push(p); } } int cnt = 0; while (!pq.empty()) { p = pq.top(); pq.pop(); if (!vis[p.l] && !vis[p.r]) { cnt++; vis[p.l] = 1; vis[p.r] = 1; pos.erase(p.l); pos.erase(p.r); ans.push_back(p); set<int>::iterator it = (pos.lower_bound(p.l)); int l = *(--it); it = (pos.lower_bound(p.r + 1)); int r = *it; if (l == 0 || r == n + 1) continue; if (l >= 1 && r <= n && s[l - 1] != s[r - 1]) { po q; q.l = l; q.r = r; q.diff = abs(v[q.l - 1] - v[q.r - 1]); pq.push(q); } } } cout << cnt << endl; for (int i = 0; i < ans.size(); i++) { cout << ans[i].l << " " << ans[i].r << 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 heapq import math n = int(raw_input()) bg = raw_input() bn = bg.count('B') skill = [int(i) for i in raw_input().split()] couple = [] num = [] for i in range(n-1): if bg[i] != bg[i+1]: diff = abs(skill[i] - skill[i+1]) couple.append([diff, i, i+1]) heapq.heapify(couple) flag = [0] * n before = [int(i) for i in range(n-1)] after = [int(i) for i in range(1,n)] while couple != []: trans = heapq.heappop(couple) difftrans = trans[0] bt = trans[1] at = trans[2] if flag[bt] or flag[at]: continue else: flag[bt] = 1 flag[at] = 1 num += [str(bt+1) + ' ' + str(at+1)] if bt != 0 and at != n - 1: btt = before[bt-1] att = after[at] if bg[btt] != bg[att]: heapq.heappush(couple, [abs(skill[btt] - skill[att]), btt, att]) before[att - 1] = btt after[btt] = att print (min(bn, n-bn)) print ('\n'.join(num))
PYTHON
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.util.*; import java.io.*; public class Main { 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))); StringTokenizer s = new StringTokenizer(br.readLine()); int n=Integer.parseInt(s.nextToken()); s = new StringTokenizer(br.readLine()); String str=s.nextToken(); s = new StringTokenizer(br.readLine()); int ar[]=new int[n]; int count=0; int l[]=new int[n]; int r[]=new int[n]; for(int i=0;i<n;i++) { ar[i]=Integer.parseInt(s.nextToken()); if(str.charAt(i)=='B') count++; l[i]=i-1; r[i]=i+1; } pw.println(Math.min(count, n-count)); PriorityQueue<Node>pq=new PriorityQueue<>((a,b)->(a.ti==b.ti)?a.fi-b.fi:a.ti-b.ti); for(int i=0;i<n-1;i++) { if(str.charAt(i)!=str.charAt(i+1)) pq.add(new Node(i,i+1,Math.abs(ar[i]-ar[i+1]))); } boolean visited[]=new boolean[n]; while(!pq.isEmpty()) { Node tmp=pq.poll(); if(!visited[tmp.fi] && !visited[tmp.si]) { pw.println((tmp.fi+1)+" "+(tmp.si+1)); visited[tmp.fi]=true; visited[tmp.si]=true; int left=l[tmp.fi]; int right=r[tmp.si]; if(right<n) l[right]=left; if(left>=0) r[left]=right; if(left>=0 && right<n && str.charAt(left)!=str.charAt(right)) { pq.add(new Node(left,right,Math.abs(ar[left]-ar[right]))); } } } pw.close(); } } class Node{ int fi; int si; int ti; public Node(int fi,int si,int ti) { this.fi=fi; this.si=si; this.ti=ti; } }
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 comment(linker, "/STACK:64000000") int n; struct man { int _dsfdsf; int _dfjdsj; void setLeft(int x) { if (x < 0 || x >= n) x = -1; _dsfdsf = x; } void setRight(int x) { if (x < 0 || x >= n) x = -1; _dfjdsj = x; } void remove(); }; char s[1 << 18]; int a[1 << 18]; man b[1 << 18]; priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > q; int m; pair<int, int> ans[1 << 17]; void man::remove() { if (_dsfdsf != -1) b[_dsfdsf]._dfjdsj = _dfjdsj; if (_dfjdsj != -1) b[_dfjdsj]._dsfdsf = _dsfdsf; _dfjdsj = _dsfdsf = -1; } inline int dif(int x, int y) { return abs(x - y); } inline void init() { m = 0; scanf("%d\n", &n); gets(s); for (int i = 0; i < n; ++i) { scanf("%d", &a[i]); b[i].setLeft(i - 1); b[i].setRight(i + 1); } for (int i = 1; i < n; ++i) { if (s[i - 1] == s[i]) continue; pair<int, int> tmp(dif(a[i - 1], a[i]), i - 1); q.push(tmp); } } int main() { init(); while (!q.empty()) { pair<int, int> cur = q.top(); q.pop(); int x = cur.second; int y = b[cur.second]._dfjdsj; if (y == -1 || dif(a[x], a[y]) != cur.first) continue; ans[m++] = pair<int, int>(x + 1, y + 1); int _dsfdsf = b[x]._dsfdsf; int _dfjdsj = b[y]._dfjdsj; if (_dsfdsf != -1 && _dfjdsj != -1 && s[_dsfdsf] != s[_dfjdsj]) { pair<int, int> tmp = pair<int, int>(dif(a[_dsfdsf], a[_dfjdsj]), _dsfdsf); q.push(tmp); } b[x].remove(); b[y].remove(); } printf("%d\n", m); for (int i = 0; i < m; ++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; inline void pisz(int n) { printf("%d\n", n); } template <typename T, typename TT> ostream& operator<<(ostream& s, pair<T, TT> t) { return s << "(" << t.first << "," << t.second << ")"; } template <typename T> ostream& operator<<(ostream& s, vector<T> t) { for (int(i) = 0; (i) < (((int)(t.size()))); ++(i)) s << t[i] << " "; return s; } int a[200006]; int val[200006]; char plec[200006]; set<int> dance; void recalcval(int i) { set<int>::iterator it = dance.upper_bound(i); if (it == dance.end()) { val[i] = 1000000000; return; } int k = *it; val[i] = (plec[k] == plec[i]) ? 1000000000 : abs(a[i] - a[k]); } int main() { int(n); scanf("%d", &(n)); scanf("%s", plec); for (int(i) = 0; (i) < (n); ++(i)) scanf("%d", a + i); for (int(i) = 0; (i) < (n); ++(i)) dance.insert(i); vector<pair<int, int> > res; for (int(i) = 0; (i) < (n); ++(i)) recalcval(i); set<pair<int, int> > st; for (int(i) = 0; (i) < (n); ++(i)) st.insert(make_pair(val[i], i)); while (!st.empty()) { if (st.begin()->first == 1000000000) break; int i = st.begin()->second; int k = *dance.upper_bound(i); int rest = -1; set<int>::iterator it = dance.find(i); if (it != dance.begin()) { --it; rest = *it; } st.erase(make_pair(val[i], i)); st.erase(make_pair(val[k], k)); dance.erase(i); dance.erase(k); if (rest != -1) { st.erase(make_pair(val[rest], rest)); recalcval(rest); st.insert(make_pair(val[rest], rest)); } res.push_back(make_pair(i, k)); } pisz(((int)(res.size()))); for (int(i) = 0; (i) < (((int)(res.size()))); ++(i)) printf("%d %d\n", res[i].first + 1, res[i].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
#include <bits/stdc++.h> using namespace std; int skil[200007], pre[200007], post[200007]; bool flag[200007]; char s[200007]; struct data { int l, r; data() {} data(int a, int b) { l = a; r = b; } bool operator<(const data& a) const { return abs(skil[l] - skil[r]) == abs(skil[a.l] - skil[a.r]) ? (l > a.l) : abs(skil[l] - skil[r]) > abs(skil[a.l] - skil[a.r]); } }; int main() { int n, i, b, g; priority_queue<data> pq; scanf("%d", &n); getchar(); scanf("%s", &s[1]); s[0] = s[1]; s[n + 1] = s[n]; for (i = 1, b = g = 0; i <= n; i++) { scanf("%d", &skil[i]); pre[i] = i - 1; post[i] = i + 1; if (s[i] == 'B') b++; else g++; if (s[i] ^ s[i - 1]) { pq.push(data(i - 1, i)); } } printf("%d\n", min(b, g)); flag[0] = flag[n + 1] = true; while (!pq.empty()) { data u = pq.top(); pq.pop(); if (flag[u.l] || flag[u.r]) continue; printf("%d %d\n", u.l, u.r); flag[u.l] = flag[u.r] = true; post[pre[u.l]] = post[u.r]; pre[post[u.r]] = pre[u.l]; { if (s[pre[u.l]] ^ s[post[u.r]]) { pq.push(data(pre[u.l], post[u.r])); } } } 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 skill[100011 * 2], vis[100011 * 2]; int rgh[100011 * 2], lf[100011 * 2]; int cup, n; char s[100011 * 2]; struct node { int l, r, c; bool operator<(const node &a) const { if (c == a.c) return l > a.l; else return c > a.c; } } tmp; priority_queue<node> que; void init() { memset(vis, 0, sizeof(vis)); while (!que.empty()) que.pop(); cup = 0; } int main() { int i; while (scanf("%d", &n) != EOF) { init(); scanf("%s", s + 1); for (i = 1; i <= n; i++) { scanf("%d", &skill[i]); lf[i] = i - 1; rgh[i] = i + 1; if (s[i] == 'B') cup++; } cup = min(n - cup, cup); printf("%d\n", cup); for (i = 1; i < n; i++) if (s[i] != s[i + 1]) { tmp.l = i; tmp.r = i + 1; tmp.c = abs(skill[i] - skill[i + 1]); que.push(tmp); } while (cup--) { while (!que.empty()) { tmp = que.top(); que.pop(); if (vis[tmp.l] == 0 && vis[tmp.r] == 0) { printf("%d %d\n", tmp.l, tmp.r); vis[tmp.l] = vis[tmp.r] = 1; break; } } int ll = lf[tmp.l], rr = rgh[tmp.r]; rgh[ll] = rr; lf[rr] = ll; if (ll > 0 && rr <= n && s[ll] != s[rr]) { tmp.l = ll; tmp.r = rr; tmp.c = abs(skill[ll] - skill[rr]); que.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; const int maxn = 2e5 + 10; int pre[maxn], net[maxn], val[maxn]; char str[maxn]; struct Node { int l, r, val; Node(int l = 0, int r = 0, int val = 0) : l(l), r(r), val(val) {} bool operator<(const Node &rhs) const { return val > rhs.val || (val == rhs.val && l > rhs.l); } } node[maxn]; priority_queue<Node> ss; int fabss(int x) { return x < 0 ? -x : x; } vector<Node> ans; bool vis[maxn]; bool judge(int l, int r, int n) { if (l >= 1 && r <= n && !vis[l] && !vis[r]) return true; return false; } int main() { int n; scanf("%d", &n); scanf("%s", str + 1); for (int i = 1; i <= n; i++) scanf("%d", &val[i]); ans.clear(); memset(vis, 0, sizeof(vis)); for (int i = 1; i <= n; i++) pre[i] = i - 1, net[i] = i + 1; for (int i = 1; i < n; i++) if (str[i] != str[i + 1]) ss.push(Node(i, i + 1, fabss(val[i + 1] - val[i]))); while (!ss.empty()) { Node tmp = ss.top(); ss.pop(); int l = tmp.l, r = tmp.r; if (!judge(l, r, n)) continue; vis[l] = 1, vis[r] = 1; ans.push_back(Node(l, r, 0)); int pl = pre[l], nr = net[r]; net[pl] = nr, pre[nr] = pl; if (!judge(pl, nr, n)) continue; if (str[pl] != str[nr]) ss.push(Node(pl, nr, fabss(val[pl] - val[nr]))); } int tot = ans.size(); printf("%d\n", tot); for (int i = 0; i < tot; i++) printf("%d %d\n", ans[i].l, ans[i].r); 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> template <class T> void swap(T &x, T &y) { T t = x; x = y; y = t; } int abs(int x) { return (x < 0 ? -x : x); } const int N = 200009; int n, prev[N], next[N], a[N], l, h, u[N]; char s[N]; class point { public: int a, x, y; bool operator>(const point &t) { return (a > t.a || (a == t.a && x > t.x)); } } v[N], z[N]; void pu(int d, int b, int e) { l++; v[l].a = d; v[l].x = b; v[l].y = e; int c, k; point t = v[l]; for (k = l; k / 2 > 0; k = c) { c = k / 2; if (t > v[c]) break; v[k] = v[c]; } v[k] = t; } void pop() { swap(v[1], v[l]); l--; int c, k; point t = v[1]; for (k = 1; k * 2 <= l; k = c) { c = k * 2 + 1; if (c > l || (c <= l && v[c] > v[c - 1])) c--; if (v[c] > t) break; v[k] = v[c]; } v[k] = t; } int main() { scanf("%d%s", &n, s); int i, j; for (i = 1; i <= n; i++) { scanf("%d", &a[i]); next[i] = i + 1; prev[i] = i - 1; if (i > 1 && s[i - 1] != s[i - 2]) pu(abs(a[i] - a[i - 1]), i - 1, i); } for (; l > 0;) { point t = v[1]; pop(); i = t.x; j = t.y; if (u[i] || u[j]) continue; u[i] = u[j] = 1; z[h] = t; h++; if (prev[i] > 0) next[prev[i]] = next[j]; if (next[j] <= n) prev[next[j]] = prev[i]; if (prev[i] > 0 && next[j] <= n && s[prev[i] - 1] != s[next[j] - 1]) pu(abs(a[prev[i]] - a[next[j]]), prev[i], next[j]); } printf("%d\n", h); for (i = 0; i < h; i++) printf("%d %d\n", z[i].x, z[i].y); }
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.*; //School Team Contest #3 (Winter Computer School 2010/11), C public class DancingLessons2 { private static class Person implements Comparable<Person> { final boolean sex; final int skill; final int position; Person(int position, boolean sex, int skill) { this.sex = sex; this.skill = skill; this.position = position; } int diff = Integer.MAX_VALUE; public int compareTo(Person o) { int result = diff - o.diff; if(result == 0) result = position - o.position; return result; } Person next, previous; } public static void main(String[] args) throws IOException { File file = new File("input.txt"); if(file.exists()) System.setIn(new FileInputStream(file)); BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); int k = Integer.parseInt(r.readLine()); assert k > 0; String s = r.readLine(); assert s.length() == k && s.matches("[BG]+"); String ss[] = r.readLine().split(" "); assert ss.length == k; List<Person> persons = new ArrayList<Person>(k); for(int i = 0; i < k; i++) persons.add(new Person(i, s.charAt(i) == 'B', Integer.parseInt(ss[i]))); List<int[]> results = solve2(persons); System.out.println(results.size()); for(int[] result : results) System.out.println((result[0] + 1) + " " + (result[1] + 1)); } private static List<int[]> solve2(List<Person> persons) { TreeSet<Person> diffs = new TreeSet<Person>(); for(int i = 1; i < persons.size(); i++) { Person p1 = persons.get(i - 1), p2 = persons.get(i); p1.next = p2; p2.previous = p1; if(p1.sex ^ p2.sex) { p1.diff = Math.abs(p1.skill - p2.skill); diffs.add(p1); } } List<int[]> results = new ArrayList<int[]>(persons.size() / 2); while(diffs.size() > 0) { Person p1 = diffs.pollFirst(), p2 = p1.next; results.add(new int[] {p1.position, p2.position}); diffs.remove(p2); p1 = p1.previous; p2 = p2.next; if(p1 != null) { p1.next = p2; if(p2 != null) { p2.previous = p1; diffs.remove(p1); if(p1.sex ^ p2.sex) { p1.diff = Math.abs(p1.skill - p2.skill); diffs.add(p1); } } else diffs.remove(p1); } else if(p2 != null) p2.previous = null; else break; } return results; } }
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; template <class T, class S> ostream& operator<<(ostream& os, const pair<T, S>& v) { return os << "(" << v.first << ", " << v.second << ")"; } template <class T> ostream& operator<<(ostream& os, const vector<T>& v) { os << "["; for (int i = int(0); i <= int((static_cast<int>((v).size())) - 1); ++i) { if (i) os << ", "; os << v[i]; } return os << "]"; } template <class T> bool setmax(T& _a, T _b) { if (_b > _a) { _a = _b; return true; } return false; } template <class T> bool setmin(T& _a, T _b) { if (_b < _a) { _a = _b; return true; } return false; } template <class T> T gcd(T _a, T _b) { return _b == 0 ? _a : gcd(_b, _a % _b); } const int N = 200000; struct Node { int i, a; bool sex; Node *prev, *next; } a[N]; set<pair<int, int> > s; void add(Node* p) { if (p == nullptr || p->next == nullptr) return; if (p->sex != p->next->sex) { s.insert(make_pair(abs(p->a - p->next->a), p->i)); } } void erase(Node* p) { if (p == nullptr || p->next == nullptr) return; if (p->sex != p->next->sex) { s.erase(make_pair(abs(p->a - p->next->a), p->i)); } } int main() { int n; scanf("%d", &n); string sex; cin >> sex; for (int i = int(0); i <= int((n)-1); ++i) { scanf("%d", &a[i].a); a[i].i = i, a[i].sex = (sex[i] == 'B'); a[i].prev = (i == 0 ? nullptr : a + i - 1); a[i].next = (i == n - 1 ? nullptr : a + i + 1); } for (int i = int(0); i <= int((n)-1); ++i) add(a + i); vector<pair<int, int> > ans; while (!s.empty()) { const int i = s.begin()->second, j = a[i].next->i; ans.push_back(make_pair(i, j)); Node *l = a[i].prev, *r = a[j].next; erase(l), erase(a + i), erase(a + j); if (l) l->next = r; if (r) r->prev = l; add(l); } printf("%d\n", static_cast<int>((ans).size())); for (pair<int, int> p : ans) printf("%d %d\n", p.first + 1, p.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
import heapq import math n = int(raw_input()) bg = raw_input() bn = bg.count('B') skill = [int(i) for i in raw_input().split()] couple = [] num = [] for i in range(n-1): if bg[i] != bg[i+1]: diff = abs(skill[i] - skill[i+1]) couple.append([diff, i, i+1]) heapq.heapify(couple) #以两数差值为选择的序号堆排序 flag = [0] * n before = [int(i) for i in range(n-1)] after = [int(i) for i in range(1,n)] #分别记录每个序号的前一个数和后一个数 while couple != []: trans = heapq.heappop(couple) #把堆排序的最小pop出来,符合题目要求 difftrans = trans[0] bt = trans[1] at = trans[2] if flag[bt] or flag[at]: #查是否被选出 continue else: flag[bt] = 1 flag[at] = 1 num += [str(bt+1) + ' ' + str(at+1)] #输出项 if bt != 0 and at != n - 1: btt = before[bt-1] #获取下一组的序号 att = after[at] if bg[btt] != bg[att]: #如果是一男一女则将其加入到堆中 heapq.heappush(couple, [abs(skill[btt] - skill[att]), btt, att]) before[att - 1] = btt #把新的一组的前后顺序更新 after[btt] = att print (min(bn, n-bn)) print ('\n'.join(num))
PYTHON
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; char s[200022]; int ans[200022][3]; int ansLen; int abs(int a) { return a < 0 ? -a : a; } int Diff(int a, int b) { if (a < 0 && b > 0 || a > 0 && b < 0) return abs(a + b); return 1000000000; } struct bnode { int num; bnode *pre, *next; int d[500]; int min, optPos; int id[500]; int tail; } block[520]; void Update(int v, bool t = false) { if (t) { block[v].min = 1000000000; for (int i = 0; i < block[v].tail; i++) { int last = Diff(block[v].d[i], block[v].d[i + 1]); if (last < block[v].min) { block[v].min = last; block[v].optPos = i; } } } if (!block[v].next) return; int last = Diff(block[v].next->d[0], block[v].d[block[v].tail]); if (block[v].tail == 0) block[v].min = 1000000000; if (last < block[v].min) { block[v].min = last; block[v].optPos = block[v].tail; } } void DeleteB(int v) { if (block[v].pre) block[v].pre->next = block[v].next; if (block[v].next) block[v].next->pre = block[v].pre; } void DeleteP(int v, int pos) { for (int j = pos; j < block[v].tail; j++) { block[v].d[j] = block[v].d[j + 1]; block[v].id[j] = block[v].id[j + 1]; } block[v].tail--; if (block[v].tail == -1) DeleteB(v); else Update(v, true); if (block[v].pre) Update(block[v].pre->num, true); } bool Dance() { int min = 1000000000, v; for (bnode *pb = block[0].next; pb; pb = pb->next) if (pb->min < min) min = pb->min, v = pb->num; if (min == 1000000000) return false; ansLen++; ans[ansLen][2] = min; if (block[v].optPos == block[v].tail) { ans[ansLen][0] = block[v].id[block[v].tail]; ans[ansLen][1] = block[v].next->id[0]; DeleteP(v, block[v].tail); DeleteP(block[v].next->num, 0); } else { ans[ansLen][0] = block[v].id[block[v].optPos]; ans[ansLen][1] = block[v].id[block[v].optPos + 1]; int t = block[v].optPos; DeleteP(v, t); DeleteP(v, t); } return true; } void Init() { block[0].next = &block[1]; for (int i = 1; i <= n / 500 + 1; i++) { block[i].num = i; block[i].pre = &block[i - 1]; block[i].next = &block[i + 1]; block[i].min = 1000000000; } block[(n - 1) / 500 + 1].next = 0; } int main() { ansLen = 0; scanf("%d", &n); scanf("%s", s); Init(); for (int i = 0; i < n; i++) { block[i / 500 + 1].d[i % 500] = s[i] == 'B' ? -1 : 1; block[i / 500 + 1].id[i % 500] = i + 1; block[i / 500 + 1].tail = i % 500; } for (int i = 0; i < n; i++) { int t; scanf("%d", &t); block[i / 500 + 1].d[i % 500] *= t; } for (int i = 1; i <= n / 500 + 1; i++) Update(i, true); while (Dance()) ; printf("%d\n", ansLen); for (int i = 1; i <= ansLen; 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 N = 2 * 1e5 + 10; int n; struct Node { int left; int right; int diff; }; int ll[N]; int rr[N]; int level[N]; char sex[N]; bool vis[N]; struct cmp { bool operator()(Node x, Node y) { if (x.diff != y.diff) return x.diff > y.diff; else return x.left > y.left; } }; priority_queue<Node, vector<Node>, cmp> que; queue<Node> que1; int main() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> n; int cnt = 0; for (int i = 1; i <= n; ++i) { cin >> sex[i]; ll[i] = i - 1; rr[i] = i + 1; if (sex[i] == 'B') ++cnt; } for (int i = 1; i <= n; ++i) { cin >> level[i]; } cnt = min(cnt, n - cnt); for (int i = 1; i < n; ++i) { if (sex[i] != sex[i + 1]) { Node p; p.left = i; p.right = i + 1; p.diff = abs(level[i + 1] - level[i]); que.push(p); } } while (cnt--) { Node p; while (!que.empty()) { p = que.top(); que.pop(); if (p.left > p.right) swap(p.left, p.right); if (!vis[p.left] && !vis[p.right]) { vis[p.left] = true; vis[p.right] = true; que1.push(p); break; } } int nl = ll[p.left]; int nr = rr[p.right]; rr[nl] = nr; ll[nr] = nl; if (nl >= 1 && nl <= n && nr >= 1 && nr <= n) { if (sex[nl] != sex[nr]) { Node q; q.left = nl; q.right = nr; q.diff = abs(level[nl] - level[nr]); que.push(q); } } } cout << que1.size() << endl; while (!que1.empty()) { Node p = que1.front(); que1.pop(); cout << p.left << " " << p.right << 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 = 2e5 + 7; int a[MAXN], n; set<int> ind; set<pair<int, pair<int, int> > > x; string s; void rem(int p, int q) { ind.erase(p); ind.erase(q); auto l = ind.lower_bound(p); auto r = ind.lower_bound(q); if (l != ind.begin()) { --l; x.erase({abs(a[*l] - a[p]), {*l, p}}); ++l; } if (r != ind.end()) x.erase({abs(a[*r] - a[q]), {q, *r}}); if (l != ind.begin() && r != ind.end()) { --l; if (s[*l] != s[*r]) x.insert({abs(a[*l] - a[*r]), {*l, *r}}); } } int main() { ios::sync_with_stdio(0); cin >> n >> s; s = "*" + s; for (int i = 1; i <= n; ++i) { cin >> a[i]; ind.insert(i); } for (int i = 1; i < n; ++i) if (s[i] != s[i + 1]) x.insert({abs(a[i + 1] - a[i]), {i, i + 1}}); vector<pair<int, int> > ans; while (!x.empty()) { int p = (*x.begin()).second.first; int q = (*x.begin()).second.second; x.erase(x.begin()); ans.push_back({p, q}); rem(p, q); } cout << ans.size() << '\n'; for (auto p : ans) cout << p.first << ' ' << p.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
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) 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)) L,R=LMap[L],RMap[R] if L>=1 and R<=n : 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
import java.io.*; import java.util.*; //School Team Contest #3 (Winter Computer School 2010/11), C public class DancingLessons { private static class Person implements Comparable<Person> { final boolean sex; final int skill; final int position; Person(int position, boolean sex, int skill) { this.sex = sex; this.skill = skill; this.position = position; } int diff = Integer.MAX_VALUE; public int compareTo(int diff, int position) { int result = this.diff - diff; if(result == 0) result = this.position - position; return result; } public int compareTo(Person o) { int result = diff - o.diff; if(result == 0) result = position - o.position; return result; } Person next, previous; @Override public String toString() { return diff + "(" + position + "/" + (sex ? 'M' : 'F') + "/" + skill + ")"; } } public static void main(String[] args) throws IOException { File file = new File("input.txt"); if(file.exists()) System.setIn(new FileInputStream(file)); BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); int k = Integer.parseInt(r.readLine()); assert k > 0; String s = r.readLine(); assert s.length() == k && s.matches("[BG]+"); String ss[] = r.readLine().split(" "); assert ss.length == k; List<Person> persons = new ArrayList<Person>(k); for(int i = 0; i < k; i++) persons.add(new Person(i, s.charAt(i) == 'B', Integer.parseInt(ss[i]))); List<int[]> results = solve2(persons); System.out.println(results.size()); for(int[] result : results) System.out.println((result[0] + 1) + " " + (result[1] + 1)); } private static List<int[]> solve(List<Person> persons) { int top = 0, bottom = 0; Person diffs[] = new Person[persons.size()]; for(int i = 1; i < persons.size(); i++) { Person p1 = persons.get(i - 1), p2 = persons.get(i); p1.next = p2; p2.previous = p1; if(p1.sex ^ p2.sex) { p1.diff = Math.abs(p1.skill - p2.skill); diffs[top++] = p1; } } qsort(diffs, bottom, top - 1); List<int[]> results = new ArrayList<int[]>(persons.size() / 2); while(bottom != top) { //System.out.println(bottom + "/" + top + " " + Arrays.toString(diffs)); Person p1 = diffs[bottom]; bottom++; //if(p1 == null || p1.diff == Integer.MAX_VALUE) // continue; Person p2 = p1.next; results.add(new int[] {p1.position, p2.position}); { int i2 = -1; for(int lo = bottom, hi = top; lo != hi;) { int m = (lo + hi) / 2, v = p2.compareTo(diffs[m]); if(v < 0) hi = m; else if(v > 0) lo = m + 1; else { i2 = m; break; } } if(i2 != -1) { if(i2 <= (top + bottom) / 2) System.arraycopy(diffs, bottom, diffs, bottom + 1, i2 - bottom++); else System.arraycopy(diffs, i2 + 1, diffs, i2, --top - i2); } } //p1.diff = Integer.MAX_VALUE; //p2.diff = Integer.MAX_VALUE; p1 = p1.previous; p2 = p2.next; if(p1 != null) { p1.next = p2; if(p2 != null) { p2.previous = p1; int p = -1; for(int lo = bottom, hi = top; lo != hi;) { int m = (lo + hi) / 2, v = p1.compareTo(diffs[m]); if(v < 0) hi = m; else if(v > 0) lo = m + 1; else { p = m; break; } } int diff = p1.sex ^ p2.sex ? Math.abs(p1.skill - p2.skill) : Integer.MAX_VALUE; int lo = bottom, hi = top; while(lo != hi) { int m = (lo + hi) / 2; if(diffs[m].compareTo(diff, p1.position) >= 0) hi = m; else lo = m + 1; } p1.diff = diff; if(p != -1) { if(p < lo) { lo--; System.arraycopy(diffs, p + 1, diffs, p, lo - p); } else if(lo < p) System.arraycopy(diffs, lo, diffs, lo + 1, p - lo); if(diff != Integer.MAX_VALUE) diffs[lo] = p1; else { assert lo == top - 1; top--; } } else if(diff != Integer.MAX_VALUE) { if(bottom > 0 && lo <= (top + bottom) / 2) { System.arraycopy(diffs, bottom, diffs, bottom - 1, lo - bottom--); diffs[lo - 1] = p1; } else { System.arraycopy(diffs, lo, diffs, lo + 1, top++ - lo); diffs[lo] = p1; } } } else { int i1 = -1; for(int lo = bottom, hi = top; lo != hi;) { int m = (lo + hi) / 2, v = p1.compareTo(diffs[m]); if(v < 0) hi = m; else if(v > 0) lo = m + 1; else { i1 = m; break; } } if(i1 != -1) { if(i1 <= (top + bottom) / 2) System.arraycopy(diffs, bottom, diffs, bottom + 1, i1 - bottom++); else System.arraycopy(diffs, i1 + 1, diffs, i1, --top - i1); } //p1.diff = Integer.MAX_VALUE; } } else if(p2 != null) p2.previous = null; else break; } return results; } private static List<int[]> solve2(List<Person> persons) { TreeSet<Person> diffs = new TreeSet<Person>(); for(int i = 1; i < persons.size(); i++) { Person p1 = persons.get(i - 1), p2 = persons.get(i); p1.next = p2; p2.previous = p1; if(p1.sex ^ p2.sex) { p1.diff = Math.abs(p1.skill - p2.skill); diffs.add(p1); } } List<int[]> results = new ArrayList<int[]>(persons.size() / 2); while(diffs.size() > 0) { //System.out.println(Arrays.toString(diffs.toArray())); Person p1 = diffs.pollFirst(), p2 = p1.next; results.add(new int[] {p1.position, p2.position}); diffs.remove(p2); p1 = p1.previous; p2 = p2.next; if(p1 != null) { p1.next = p2; if(p2 != null) { p2.previous = p1; diffs.remove(p1); if(p1.sex ^ p2.sex) { p1.diff = Math.abs(p1.skill - p2.skill); diffs.add(p1); } } else diffs.remove(p1); } else if(p2 != null) p2.previous = null; else break; } return results; } private static List<int[]> solve1(List<Person> persons) { Person diffs[] = persons.toArray(new Person[persons.size()]); for(int i = 1; i < persons.size(); i++) { Person p1 = persons.get(i - 1), p2 = persons.get(i); p1.next = p2; p2.previous = p1; p1.diff = p1.sex ^ p2.sex ? Math.abs(p1.skill - p2.skill) : Integer.MAX_VALUE; } qsort(diffs); List<int[]> results = new ArrayList<int[]>(persons.size() / 2); for(;;) { isort(diffs); if(diffs[0].diff == Integer.MAX_VALUE) break; Person p1 = diffs[0], p2 = p1.next; results.add(new int[] {p1.position, p2.position}); p1.diff = Integer.MAX_VALUE; p2.diff = Integer.MAX_VALUE; p1 = p1.previous; p2 = p2.next; if(p1 != null) { p1.next = p2; if(p2 != null) { p2.previous = p1; p1.diff = p1.sex ^ p2.sex ? Math.abs(p1.skill - p2.skill) : Integer.MAX_VALUE; } else p1.diff = Integer.MAX_VALUE; } else if(p2 != null) p2.previous = null; else break; } return results; } private static Random random; private static void test() { if(random == null) random = new Random(1); int n = 1 + random.nextInt(200000); List<Person> persons = new ArrayList<Person>(n); for(int i = 0; i < n; i++) persons.add(new Person(i, random.nextBoolean(), 1 + random.nextInt((int)1e7))); long startTime = System.currentTimeMillis(); List<int[]> results2 = solve2(persons); System.out.println(System.currentTimeMillis() - startTime); //System.out.println(Arrays.deepToString(results2.toArray())); if(n <= 1000) { List<int[]> results1 = solve1(persons); //System.out.println(Arrays.deepToString(results1.toArray())); assert results1.size() == results2.size(); for(int i = Math.min(results1.size(), results2.size()) - 1; i >= 0; i--) assert Arrays.equals(results1.get(i), results2.get(i)); } } private static <T extends Comparable<T>> void isort(T[] a) { isort(a, 0, a.length - 1); } private static <T extends Comparable<T>> void isort(T[] a, int lo, int hi) { for(int i = lo + 1, j; i <= hi; i++) { T m = a[i]; for(j = i - 1; j >= lo && a[j].compareTo(m) > 0; j--) a[j + 1] = a[j]; a[j + 1] = m; } } private static final int H[] = new int[] {1, 4, 9, 24, 85, 126}; private static <T extends Comparable<T>> void ssort(T[] a, int lo, int hi) { for(int k = H.length - 1; k >= 0; k--) { for(int h = H[k], i = lo + h, j; i <= hi; i++) { T m = a[i]; for(j = i - h; j >= lo && a[j].compareTo(m) > 0; j -= h) a[j + h] = a[j]; a[j + h] = m; } } } private static <T extends Comparable<T>> void qsort(T[] a) { qsort(a, 0, a.length - 1); } private static <T extends Comparable<T>> void qsort(T[] a, int lo, int hi) { for(;;) { if(hi - lo < 256) { ssort(a, lo, hi); return; } int i = lo, j = hi; for(T m = a[(lo + hi) / 2];;) { while(i < hi && a[i].compareTo(m) < 0) i++; while(j > lo && a[j].compareTo(m) > 0) j--; if(i >= j) break; T t = a[i]; a[i++] = a[j]; a[j--] = t; } if((--i - lo) < (hi - ++j)) { qsort(a, lo, i); lo = j; } else { qsort(a, j, hi); hi = i; } } } }
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 INF = ~0u / 2; struct Node { int left, right, key; }; bool operator<(Node a, Node b) { if (a.key != b.key) return a.key < b.key; else if (a.left != b.left) return a.left < b.left; return a.right < b.right; } int n; string s; int List[(2 * 100000) + 100]; set<int> Lop; set<Node> S; vector<int> V; int abs(int m) { if (m < 0) m *= -1; return m; } void Input() { Node N; cin >> n; cin >> s; cin >> List[0]; Lop.insert(0); for (int i = 1; i < n; i++) { cin >> List[i]; N.left = i - 1; N.right = i; if (s[i - 1] != s[i]) { N.key = abs(List[i] - List[i - 1]); } else { N.key = INF; } S.insert(N); Lop.insert(i); } } void Run() { Node N, M; int a, b; set<int>::iterator it; while (S.size() != 0 && (*S.begin()).key != INF) { N = *S.begin(); S.erase(N); V.push_back(N.left + 1); V.push_back(N.right + 1); it = Lop.find(N.left); if (it == Lop.begin()) { a = -1; } else { it--; a = (*it); } it = Lop.find(N.right); it++; if (it == Lop.end()) { b = -1; } else { b = (*it); } if (a != -1) { M.left = a; M.right = N.left; if (s[a] == s[N.left]) M.key = INF; else M.key = abs(List[a] - List[N.left]); S.erase(M); } if (b != -1) { M.left = N.right; M.right = b; if (s[N.right] == s[b]) M.key = INF; else M.key = abs(List[N.right] - List[b]); S.erase(M); } if (a != -1 && b != -1) { M.left = a; M.right = b; if (s[a] == s[b]) M.key = INF; else M.key = abs(List[a] - List[b]); S.insert(M); } Lop.erase(N.left); Lop.erase(N.right); } } int main() { Input(); Run(); cout << V.size() / 2 << endl; for (int i = 0; i < V.size(); i += 2) { cout << V[i] << " " << V[i + 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) 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
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; import java.util.Scanner; public class C { static class triple implements Comparable<triple> { int diff, id1, id2; public int compareTo( triple arg0) { if (this.diff==arg0.diff) return this.id1-arg0.id1; return this.diff-arg0.diff; } public triple(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{ PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); Scanner in = new Scanner(System.in); int n = in.nextInt(); char[] s = in.next().toCharArray(); int[]a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } PriorityQueue<triple> q = new PriorityQueue<triple>(); int[] left = new int[n]; int[] 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[i] != s[i+1]) q.add(new triple(a[i]-a[i+1], i, i+1)); } boolean[]used = new boolean[n]; StringBuffer sb = new StringBuffer(); int count = 0; while (!q.isEmpty()) { triple c = q.poll(); if (used[c.id1] || used[c.id2]) continue; used[c.id1] = used[c.id2] = true; sb.append((c.id1+1) + " " + (c.id2+1) +"\n"); count++; int l = left[c.id1], r = right[c.id2]; right[l] = r; left[r] = l; if (s[l] != s[r]) q.add(new triple(a[l]-a[r], l, r)); } System.out.println(count); System.out.println(sb.toString()); } }
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> struct Node { int l, r, s; }; struct Pair { int p1, p2, d; Pair(int p1, int p2, int d) : p1(p1), p2(p2), d(d) {} bool operator>(const Pair& rhs) const { return d > rhs.d || (!(rhs.d > d) && p1 > rhs.p1); } }; int main() { int n; std::string s; std::cin >> n >> s; std::vector<Node> v(n); for (int i = 0; i < n; ++i) { std::cin >> v[i].s; v[i].l = i - 1; v[i].r = i + 1; } std::priority_queue<Pair, std::vector<Pair>, std::greater<Pair> > q; for (int i = 0; i < n - 1; ++i) { if (s[i] != s[i + 1]) { q.push(Pair(i, i + 1, abs(v[i].s - v[i + 1].s))); } } std::vector<int> used(n); std::vector<std::pair<int, int> > res; while (!q.empty()) { Pair top = q.top(); q.pop(); int p1 = top.p1; int p2 = top.p2; if (used[p1] || used[p2]) { continue; } used[p1] = used[p2] = 1; res.push_back(std::make_pair(p1, p2)); Node& u = v[p1]; Node& w = v[p2]; if (0 <= u.l) { v[u.l].r = w.r; } if (w.r < n) { v[w.r].l = u.l; } if (0 <= u.l && w.r < n && s[u.l] != s[w.r]) { q.push(Pair(u.l, w.r, abs(v[u.l].s - v[w.r].s))); } } std::cout << res.size() << std::endl; for (int i = 0; i < (int)res.size(); ++i) { std::cout << res[i].first + 1 << " " << res[i].second + 1 << std::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; char s[1000000]; int a[1000000]; int l[1000000]; int r[1000000]; int visited[1000000] = {0}; int abs(int a) { if (a < 0) return -a; return a; } int main() { list<pair<int, int> > ans; priority_queue<pair<long long, pair<int, int> > > e; int n; scanf("%d", &n); 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]) { pair<long long, pair<int, int> > t; t.first = -(long long)abs(a[i] - a[i + 1]) * 1000000 - i; t.second.first = i; t.second.second = i + 1; e.push(t); } l[i] = i - 1; r[i] = i + 1; } l[0] = -1; r[n - 1] = -1; while (!e.empty()) { pair<long long, pair<int, int> > t = e.top(); e.pop(); if (!visited[t.second.first] && !visited[t.second.second]) { int c = t.second.first; int b = t.second.second; l[r[b]] = l[c]; r[l[c]] = r[b]; visited[c] = 1; visited[b] = 1; ans.push_back(pair<int, int>(c, b)); if (l[c] != -1 && r[b] != -1) { c = l[c]; b = r[b]; if (s[c] != s[b]) { pair<long long, pair<int, int> > t; t.first = -(long long)abs(a[c] - a[b]) * 1000000 - c; t.second.first = c; t.second.second = b; e.push(t); } } } } printf("%d\n", ans.size()); for (list<pair<int, int> >::iterator i = ans.begin(); i != ans.end(); i++) { printf("%d %d\n", (*i).first + 1, (*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; #pragma comment(linker, "/STACK:16777216") #pragma warning(disable : 4786) struct node { int d, x, y; node() {} node(int a, int b, int c) { x = a; y = b; d = c; } bool operator<(const node &a) const { return d > a.d || (d == a.d && x > a.x) || (d == a.d && x == a.x && y > a.y); } }; bool vi[200009]; int a[200009], l[200009], r[200009], n; priority_queue<node> q; string s; vector<pair<int, int> > res; int main() { int i; node u; cin >> n >> s; s = "a" + s; for (i = 1; i <= n; i++) { cin >> a[i]; l[i] = i - 1; r[i] = i + 1; if (i > 1 && s[i] != s[i - 1]) { q.push(node( i - 1, i, ((a[i] - a[i - 1]) < 0 ? (-(a[i] - a[i - 1])) : (a[i] - a[i - 1])))); } } while (!q.empty()) { u = q.top(); q.pop(); if (vi[u.x] || vi[u.y]) continue; res.push_back(pair<int, int>(u.x, u.y)); vi[u.x] = vi[u.y] = 1; if (l[u.x] > 0 && r[u.y] <= n && s[l[u.x]] != s[r[u.y]]) q.push(node(l[u.x], r[u.y], ((a[l[u.x]] - a[r[u.y]]) < 0 ? (-(a[l[u.x]] - a[r[u.y]])) : (a[l[u.x]] - a[r[u.y]])))); r[l[u.x]] = r[u.y]; l[r[u.y]] = l[u.x]; } cout << res.size() << endl; for (i = 0; i < res.size(); i++) { cout << res[i].first << " " << res[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
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; inline int Abs(int x) { return x > 0 ? x : -x; } set<int> peo; set<int>::iterator p1, p2; bool vis[200050], boy[200050]; char s[200050]; int a[200050]; struct node { int l, r; int val; node(int a = 0, int b = 0, int c = 0) : l(a), r(b), val(c) {} bool operator<(const node &x) const { if (val != x.val) return x.val > val; if (x.l != l) return x.l > l; return x.r > r; } }; set<node> myset; set<node>::iterator it; vector<node> ans; void work() { while (myset.size()) { it = myset.begin(); node u = *it; myset.erase(it); if (vis[u.l] || vis[u.r]) continue; vis[u.l] = vis[u.r] = 1; ans.push_back(u); p1 = peo.find(u.l); if (p1 == peo.begin()) { peo.erase(p1); peo.erase(u.r); continue; } p2 = peo.find(u.r); p2++; if (p2 == peo.end()) { peo.erase(p1); peo.erase(u.r); continue; } p1--; peo.erase(u.l); peo.erase(u.r); u.l = *p1; u.r = *p2; if (boy[u.l] == boy[u.r]) continue; u.val = Abs(a[u.l] - a[u.r]); myset.insert(u); } } int n; int main() { int i, j; while (cin >> n) { myset.clear(); peo.clear(); scanf("%s", s + 1); for (i = 1; i <= n; i++) scanf("%d", &a[i]); boy[1] = (s[1] == 'B'); for (i = 1; i <= n; i++) { peo.insert(i); boy[i + 1] = (s[i + 1] == 'B'); if (i < n && boy[i] != boy[i + 1]) myset.insert(node(i, i + 1, Abs(a[i] - a[i + 1]))); } memset(vis, 0, sizeof vis); ans.clear(); work(); cout << ans.size() << endl; for (i = 0; i < ans.size(); i++) printf("%d %d\n", ans[i].l, ans[i].r); } 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=[(abs(skl[i]-skl[i+1]),i+1,i+2) for i in range(n-1) if symbols[i]!=symbols[i+1] ] 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) 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; struct node { int diff; int st, ed; }; bool operator<(node a, node b) { if (a.diff < b.diff) return 0; if (a.diff == b.diff && a.st < b.st) return 0; return 1; }; struct Out { int st, ed; }; Out ans[100005]; char s[2 * 100005]; bool flag[2 * 100005]; int v[2 * 100005]; priority_queue<node> Q; int n, k; int tol[2 * 100005], tor[2 * 100005]; void Add(int l, int r) { int a, b; a = l; b = r; while (l >= 0 && flag[l]) l = tol[l]; while (r < n && flag[r]) r = tor[r]; tol[b] = l; tor[a] = r; if (l >= 0 && !flag[l] && r < n && !flag[r]) { if ((s[l] == 'B' && s[r] == 'G') || s[l] == 'G' && s[r] == 'B') { node temp; temp.st = l; temp.ed = r; temp.diff = abs(v[l] - v[r]); Q.push(temp); } } } void work(int n) { node temp; int i; while (Q.size()) Q.pop(); memset(flag, 0, sizeof(flag)); k = 0; for (i = 0; i < n; i++) { tol[i] = i - 1; tor[i] = i + 1; } for (i = 0; i < n - 1; i++) { if ((s[i] == 'B' && s[i + 1] == 'G') || s[i] == 'G' && s[i + 1] == 'B') { temp.st = i; temp.ed = i + 1; temp.diff = abs(v[i] - v[i + 1]); Q.push(temp); } } while (Q.size()) { temp = Q.top(); Q.pop(); if (flag[temp.st] || flag[temp.ed]) continue; k++; ans[k].st = temp.st + 1; ans[k].ed = temp.ed + 1; flag[temp.st] = 1; flag[temp.ed] = 1; Add(temp.st, temp.ed); } } void Output(int k) { int i; printf("%d\n", k); for (i = 1; i <= k; i++) printf("%d %d\n", ans[i].st, ans[i].ed); } int main() { int i; while (scanf("%d", &n) != EOF) { scanf("%s", s); for (i = 0; i < n; i++) scanf("%d", &v[i]); work(n); Output(k); } 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 get_int() { int val = 0, c = 0; for (; !isdigit(c); c = getchar()) ; for (; isdigit(c); c = getchar()) val = val * 10 + (c - '0'); return val; } struct one { int s, w, l, r, y; }; struct two { int i, j, w; }; int n, b2_cache = 0; vector<one> a; list<two> b, b2, c; list<two>::iterator b2_min; bool operator<(const two &t1, const two &t2) { return t1.w < t2.w || (t1.w == t2.w && t1.i < t2.i); }; bool valid(two &t) { return a[t.i].y & a[t.j].y; } list<two>::iterator b2_min_element() { if (b2_cache == 0) b2_min = min_element(b2.begin(), b2.end()), b2_cache = 1; return b2_min; } void maybe(int i, int j) { if (a[i].s != a[j].s) { two t = {i, j, abs(a[i].w - a[j].w)}; b2.push_back(t); b2_cache = 0; } } bool next() { if (b2.size() > 800 || b2.size() > b.size()) b2.sort(), b.merge(b2), b2_cache = 0; return b.size() + b2.size(); } two front() { two t, t1, t2; list<two>::iterator i; if (b2.empty()) t = b.front(), b.pop_front(); else { t1 = b.front(), i = b2_min_element(), t2 = *i; if (t1 < t2) t = t1, b.pop_front(); else t = t2, b2.erase(i), b2_cache = 0; } return t; } int main() { scanf("%d ", &n); a.resize(n); char s[n + 1]; gets(s); int w, i; for (i = 0; i < n; i++) w = get_int(), a[i] = {s[i] == 'B', w, i - 1, i + 1, 1}; for (i = 0; i < n - 1; i++) maybe(i, i + 1); b.sort(); while (next()) { two t = front(); if (!valid(t)) continue; c.push_back(t); one &a1 = a[t.i], &a2 = a[t.j]; a1.y = 0; a2.y = 0; if (a1.l >= 0) a[a1.l].r = a2.r; if (a2.r < n) a[a2.r].l = a1.l; if (a1.l >= 0 && a2.r < n) maybe(a1.l, a2.r); } printf("%d\n", c.size()); for (two &t : c) printf("%d %d\n", t.i + 1, t.j + 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.util.InputMismatchException; import java.io.*; import java.util.*; /** * Generated by Contest helper plug-in * Actual solution is at the bottom */ public class Main { public static void main(String[] args) { InputReader in = new StreamInputReader(System.in); PrintWriter out = new PrintWriter(System.out); run(in, out); } public static void run(InputReader in, PrintWriter out) { Solver solver = new Dancing(); solver.solve(1, in, out); Exit.exit(in, out); } } class StreamInputReader extends InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; public StreamInputReader(InputStream stream) { this.stream = stream; curChar = 0; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } @Override public void close() { try { stream.close(); } catch (IOException ignored) { } } } abstract class InputReader { private boolean finished = false; public abstract int read(); public int nextInt() { return Integer.parseInt(nextToken()); } public String nextToken() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public void setFinished(boolean finished) { this.finished = finished; } public abstract void close(); } interface Solver { public void solve(int testNumber, InputReader in, PrintWriter out); } class Exit { private Exit() { } public static void exit(InputReader in, PrintWriter out) { in.setFinished(true); in.close(); out.close(); } } class Dancing implements Solver { public void solve(int testNumber, InputReader in, PrintWriter out) { HashMap<Integer, Integer> left = new HashMap<Integer, Integer> () ; HashMap<Integer, Integer> right = new HashMap<Integer, Integer> (); int n = in.nextInt(); char [] s = in.nextToken().toCharArray(); int sex[] = new int[n]; for (int i = 0; i < s.length; i++) { sex[i] = s[i] == 'B' ? 0 : 1; } int a[] = new int[n]; for (int i = 0; i < n; ++i) { a[i] = in.nextInt(); } NavigableSet<Pair> set = new TreeSet<Pair>(new Comparator<Pair>() { public int compare(Pair pair, Pair pair1) { int d0 = Math.abs(pair.sexa - pair.sexb); int d1 = Math.abs(pair1.sexa - pair1.sexb); if (d0 - d1 != 0) return -(d0 - d1); d0 = Math.abs(pair.a0 - pair.a1); d1 = Math.abs(pair1.a0 - pair1.a1); if (d0 - d1 != 0) return d0 - d1; return Math.min(pair.index0, pair.index1) - Math.min(pair1.index0, pair1.index1); } }) ; for (int i = 0; i < n; ++i) { if (i > 0) left.put(i, i - 1); if (i != n - 1) right.put(i, i + 1); } for (int i = 0; i < n - 1; ++i) { set.add(new Pair(s[i] == 'B' ? 0 : 1, s[i + 1] == 'B' ? 0 : 1, a[i], a[i + 1], i, i + 1)); } Vector<Out> ans = new Vector<Out>() ; while (set.size() > 0) { Pair tmp = set.pollFirst(); if (tmp.sexa == tmp.sexb) break; Integer lft = left.get(tmp.index0); Integer rgh = right.get(tmp.index1); if (lft != null && lft == -1) lft = null; if (rgh != null && rgh == -1) rgh = null; ans.add(new Out(tmp.index0 + 1, tmp.index1 + 1)); if (lft != null) { set.remove(new Pair(sex[lft], sex[tmp.index0], a[lft], a[tmp.index0], lft, tmp.index0)); } if (rgh != null) { set.remove(new Pair(sex[tmp.index1], sex[rgh], a[tmp.index1], a[rgh], tmp.index1, rgh)); } if (lft != null && rgh != null) { set.add(new Pair(sex[lft], sex[rgh], a[lft], a[rgh], lft, rgh)); right.put(lft, rgh) ; left.put(rgh, lft); } if (rgh == null && lft != null) { right.put(lft, -1); } if (rgh != null && lft == null) { left.put(rgh, -1); } } out.print(ans.size() + "\n"); for (Out pair : ans) { out.println(pair); } } class Out { int a, b; Out(int a, int b) { this.a = Math.min(a, b); this.b = a + b - this.a; } @Override public String toString() { return a + " " + b ; } } class Pair { int sexa, sexb; int a0, a1; int index0, index1; Pair(int sexa, int sexb, int a0, int a1, int index0, int index1) { this.sexa = sexa; this.sexb = sexb; this.a0 = a0; this.a1 = a1; this.index0 = index0; this.index1 = index1; } } }
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 maxn = 2 * 1000 * 100 + 21; struct couple { int i, j; couple(){}; couple(int a, int b) { i = min(a, b); j = max(a, b); } }; int n; int a[maxn]; int r[maxn]; int l[maxn]; int b[maxn]; vector<pair<int, int> > ans; set<couple> s; bool operator<(const couple &c1, const couple &c2) { int a1 = abs(a[c1.j] - a[c1.i]); int a2 = abs(a[c2.j] - a[c2.i]); if (a1 != a2) return a1 < a2; return c1.i < c2.i; } void input() { ios::sync_with_stdio(false); cin.tie(0); ; cin >> n; for (int i = 0; i < n; i++) { char c; cin >> c; if (c == 'B') b[i] = 1; } for (int i = 0; i < n; i++) cin >> a[i]; } int main() { input(); l[0] = -1; r[n - 1] = -1; for (int i = 0; i < n - 1; i++) { r[i] = i + 1; l[i + 1] = i; if (b[i] != b[i + 1]) { s.insert(couple(i, i + 1)); } } while (!s.empty()) { int i = s.begin()->i; int j = s.begin()->j; s.erase(s.begin()); s.erase(couple(l[i], i)); s.erase(couple(j, r[j])); ans.push_back(make_pair(i, j)); r[l[i]] = r[j]; l[r[j]] = l[i]; if (l[i] != -1 && r[j] != -1 && b[l[i]] != b[r[j]]) s.insert(couple(l[i], r[j])); } cout << int(ans.size()) << endl; for (int i = 0; i < 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 node { node *left, *right; int skill, index; char gender; }; class item { public: node *pos; int skill, l_index, r_index; item(node *x) { assert(x->right != NULL); node *y = x->right; l_index = x->index; r_index = y->index; skill = abs((x->skill) - (y->skill)); pos = x; } }; class item_comp { public: bool operator()(const item &a, const item &b) const { if (a.skill == b.skill) return a.l_index > b.l_index; return a.skill > b.skill; } }; int main(void) { priority_queue<item, vector<item>, item_comp> Q; int n, a[100000 * 2 + 100]; char s[100000 * 2 + 100]; scanf("%d", &n); scanf("%s", s); for (register int i = (0); i < (int)n; ++i) scanf("%d", &a[i]); node *now = NULL; for (register int i = (0); i < (int)n; ++i) { node *tmp = new node; if (i) now->right = tmp; tmp->index = i; tmp->gender = s[i]; tmp->skill = a[i]; tmp->left = now; tmp->right = NULL; if (i != 0 && s[i] != s[i - 1]) { item z(now); Q.push(z); } now = tmp; } bool gone[100000 * 2 + 100]; memset(gone, 0, sizeof gone); vector<pair<int, int> > res; while (!Q.empty()) { item cur = Q.top(); Q.pop(); if (cur.pos == NULL) continue; if (cur.pos->right == NULL) continue; node *x = cur.pos; node *y = x->right; if (gone[x->index] || gone[y->index]) continue; if (cur.l_index != x->index || cur.r_index != y->index) continue; if (x->gender == y->gender) continue; if (abs((x->skill) - (y->skill)) != cur.skill) continue; res.push_back(make_pair(x->index, y->index)); gone[x->index] = gone[y->index] = true; if (x->left == NULL || y->right == NULL) continue; x->left->right = y->right; y->right->left = x->left; if (x->left->gender != y->right->gender) { Q.push(item(x->left)); } } printf("%d\n", ((int)(res).size())); for (register int i = (0); i < (int)((int)(res).size()); ++i) printf("%d %d\n", res[i].first + 1, res[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; bool gone[200004]; int main() { int n, boys = 0; cin >> n; string s; cin >> s; for (int i = 0; i < n; i++) boys += (s[i] == 'B'); int arr[n]; map<int, pair<int, int> > mp; mp[0] = {1, -1}; mp[n - 1] = {n - 2, -1}; for (int i = 0; i < n; i++) { cin >> arr[i]; if (i && i != n - 1) mp[i] = {i + 1, i - 1}; } priority_queue<pair<int, pair<int, int> > > pq; for (int i = 0; i < n - 1; i++) pq.push({-abs(arr[i] - arr[i + 1]), {-i, -(i + 1)}}); cout << min(boys, n - boys) << '\n'; while (pq.size()) { pair<int, pair<int, int> > p; p.first = pq.top().first; p.second.first = -pq.top().second.first; p.second.second = -pq.top().second.second; pq.pop(); if (gone[p.second.first] || gone[p.second.second]) continue; if (s[p.second.first] == s[p.second.second]) continue; if (p.second.first == -1 || p.second.second == -1) continue; cout << min(p.second.first + 1, p.second.second + 1) << ' ' << max(p.second.first + 1, p.second.second + 1) << '\n'; gone[p.second.first] = gone[p.second.second] = 1; int other1, other2; other1 = mp[p.second.first].first; if (other1 == p.second.second) other1 = mp[p.second.first].second; other2 = mp[p.second.second].first; if (other2 == p.second.first) other2 = mp[p.second.second].second; int o1, o2; o1 = mp[other1].first; if (o1 == p.second.first) o1 = mp[other1].second; o2 = mp[other2].first; if (o2 == p.second.second) o2 = mp[other2].second; mp[other1] = {other2, o1}; mp[other2] = {other1, o2}; pq.push({-abs(arr[other1] - arr[other2]), {-other1, -other2}}); } 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<int> S; priority_queue<pair<int, pair<int, int> >, vector<pair<int, pair<int, int> > >, greater<pair<int, pair<int, int> > > > H; int i, j, k, n, a[222222], nl, nr, sz, aa, bb, u[222222], o; pair<int, pair<int, int> > pp; set<pair<int, int> >::iterator it; char s[222222]; int next(int k) { set<int>::iterator it = S.find(k); ++it; if (it == S.end()) return -1; else return *it; } int pred(int k) { set<int>::iterator it = S.find(k); if (it == S.begin()) return -1; else { --it; return *it; } } int main() { scanf("%d", &n); gets(s); gets(s); for (i = 0; i < n; i++) if (s[i] == 'B') ++aa; else ++bb; sz = min(aa, bb); printf("%d\n", sz); for (i = 0; i < n; i++) scanf("%d", &a[i]); for (i = 1; i <= n; i++) S.insert(i); for (i = 1; i < n; i++) if (s[i - 1] != s[i]) H.push(make_pair(abs(a[i] - a[i - 1]), make_pair(i, i + 1))); o = 0; while (o != sz) { pp = H.top(); H.pop(); if (u[pp.second.first]) continue; if (u[pp.second.second]) continue; printf("%d %d\n", pp.second.first, pp.second.second); nl = pred(pp.second.first); nr = next(pp.second.second); if (nl > -1 && nr > -1 && s[nl - 1] != s[nr - 1]) H.push(make_pair(abs(a[nl - 1] - a[nr - 1]), make_pair(nl, nr))); S.erase(S.find(pp.second.first)); S.erase(S.find(pp.second.second)); u[pp.second.first] = 1; u[pp.second.second] = 1; ++o; } 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.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.io.BufferedReader; import java.io.OutputStream; import java.util.ArrayDeque; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Zyflair Griffane */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; PandaScanner in = new PandaScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); C solver = new C(); solver.solve(1, in, out); out.close(); } } class C { public void solve(int testNumber, PandaScanner in, PrintWriter out) { int n = in.nextInt(); char[] gender = in.next().toCharArray(); long[] skill = new long[n]; int[] before = new int[n]; int[] after = new int[n]; boolean[] removed = new boolean[n]; IntHeap events = new IntHeap(n); for (int i = 0; i < n; i++) { skill[i] = in.nextInt(); if (i > 0 && gender[i] != gender[i - 1]) { events.set(i, (Math.abs(skill[i] - skill[i - 1]) << 20) + i); } before[i] = i - 1; after[i] = i == n - 1 ? -1 : i + 1; } ArrayDeque<int[]> pairs = new ArrayDeque<>(); while (!events.isEmpty()) { int idx = events.poll(); if (!removed[idx] && before[idx] > -1 && gender[idx] != gender[before[idx]]) { removed[idx] = removed[before[idx]] = true; pairs.add(new int[] {before[idx] + 1, idx + 1}); int beforeIdx = before[before[idx]]; int afterIdx = after[idx]; if (beforeIdx != -1) { after[beforeIdx] = afterIdx; } if (afterIdx != -1) { before[afterIdx] = beforeIdx; if (beforeIdx != -1 && gender[beforeIdx] != gender[afterIdx]) { events.set(afterIdx, (Math.abs(skill[afterIdx] - skill[beforeIdx]) << 20) + afterIdx); } } } } out.println(pairs.size()); for (int[] pair: pairs) { out.println(pair[0] + " " + pair[1]); } } } class PandaScanner { public BufferedReader br; public StringTokenizer st; public InputStream in; public PandaScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(this.in = in)); } public String nextLine() { try { return br.readLine(); } catch (Exception e) { return null; } } public String next() { if (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine().trim()); return next(); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } class IntHeap { int d, size; int[] heap; int[] location; long[] value; public static final long INF = (long) (1e17); public IntHeap(int N) { this(N, 1); } public IntHeap(int N, int d) { this.d = d; size = 0; heap = new int[N]; location = new int[N]; value = new long[N]; Arrays.fill(value, INF); Arrays.fill(location, -1); } public boolean isEmpty() { return size == 0; } public void set(int n, long v) { if (location[n] == -1) { location[n] = size; heap[size] = n; size++; } value[n] = v; percolateDown(location[n]); percolateUp(location[n]); } public int poll() { if (size == 0) return -1; int res = heap[0]; --size; location[heap[size]] = 0; heap[0] = heap[size]; percolateDown(0); location[res] = -1; return res; } private void percolateUp(int idx) { int par = (idx - 1) >> d; while (idx != 0 && value[heap[idx]] < value[heap[par]]) { location[heap[idx]] = par; location[heap[par]] = idx; int temp = heap[idx]; heap[idx] = heap[par]; heap[par] = temp; idx = par; par = (par - 1) >> d; } } private void percolateDown(int idx) { int idx2, temp; long min; while (true) { min = Long.MAX_VALUE; idx2 = -1; temp = (idx << d) + 1; if (temp >= size) break; for (int i = 0; i < (1 << d) && temp < size; i++) { if (value[heap[temp]] < min) { min = value[heap[temp]]; idx2 = temp; } temp++; } if (value[heap[idx]] <= min) break; location[heap[idx]] = idx2; location[heap[idx2]] = idx; temp = heap[idx]; heap[idx] = heap[idx2]; heap[idx2] = temp; idx = idx2; } } }
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 java.io.*; import java.util.*; public class Main { static final boolean _DEBUG = false; private static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner(BufferedReader _br) { br = _br; } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); return ""; } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static MyScanner scan; static PrintWriter out; static int debugCount = 0; static void debug(String msg) { if (_DEBUG && debugCount < 200) { out.println(msg); out.flush(); debugCount++; } } public static void main (String args[]) throws IOException { // scan = new MyScanner(new BufferedReader(new FileReader("test.in"))); scan = new MyScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); Main inst = new Main(); inst.execute(); out.close(); } class Node { int g; int v; int id; boolean valid; Node left, right; public Node(int id) { this.id = id; g = v= -1; left = right = null; valid = true; } } class pairComp implements Comparator<int[]> { public int compare(int[] o1, int[] o2) { int dif1 = Math.abs(nodes[o1[0]].v - nodes[o1[1]].v); int dif2 = Math.abs(nodes[o2[0]].v - nodes[o2[1]].v); if (dif1 == dif2) { return o1[0] - o2[0]; } return dif1-dif2; } } int N; Node[] nodes; ArrayList<int[]> anws; PriorityQueue<int[]> pairs; void execute() { N = scan.nextInt(); nodes = new Node[N]; anws = new ArrayList<int[]>(); char[] chars = scan.next().toCharArray(); pairs = new PriorityQueue<int[]>(new pairComp()); for (int i = 0; i < N; i++) { nodes[i] = new Node(i); nodes[i].g = chars[i]-'B'; nodes[i].v = scan.nextInt(); if (i != 0) { nodes[i-1].right = nodes[i]; nodes[i].left = nodes[i-1]; if (nodes[i-1].g != nodes[i].g) { pairs.add(new int[] {i-1, i}); } } } while (!pairs.isEmpty()) { int[] pair = pairs.poll(); Node node1 = nodes[pair[0]]; Node node2 = nodes[pair[1]]; if (node1.valid && node2.valid) { anws.add(pair); node2.valid = node1.valid = false; boolean p = true; if (node1.left != null) { node1.left.right = node2.right; } else { p = false; } if (node2.right != null) { node2.right.left = node1.left; } else { p = false; } if (p && node1.left.g != node2.right.g) { pairs.add(new int[] {node1.left.id, node2.right.id}); } } } out.println(anws.size()); for (int[] pair : anws) { out.println((pair[0]+1)+" "+(pair[1]+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; set<pair<int, pair<int, int> > > S; set<pair<int, pair<int, int> > >::iterator it; pair<int, int> l[200001]; vector<pair<int, int> > ans; int a[200001], tag[200001], n; char s[200001]; int main() { scanf("%d", &n); scanf("%s", s); for (int i = 0; i < n; i++) s[i] = (s[i] == 'B' ? 0 : 1); for (int i = 0; i < n; i++) scanf("%d", &a[i]); for (int i = 0; i < n; i++) { l[i] = pair<int, int>(i - 1, i + 1); if (i != n - 1 && s[i] ^ s[i + 1] == 1) S.insert(make_pair(abs(a[i] - a[i + 1]), pair<int, int>(i, i + 1))); } while (!S.empty()) { it = S.begin(); pair<int, pair<int, int> > SV = *it; if (tag[SV.second.first] != 1 && tag[SV.second.second] != 1) { tag[SV.second.first] = tag[SV.second.second] = 1; ans.push_back(pair<int, int>(SV.second.first, SV.second.second)); int x1 = l[SV.second.first].first, x2 = l[(*it).second.second].second; if (x1 != -1) l[x1].second = x2; if (x2 != n) l[x2].first = x1; if (x1 != -1 && x2 != n && (s[x1] ^ s[x2] == 1)) S.insert(make_pair(abs(a[x1] - a[x2]), pair<int, int>(x1, x2))); } S.erase(it); } 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); 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 long long int modadd(long long int n, long long int m, long long int p = 1000000007) { return ((n + m) % p + p) % p; } inline long long int modsub(long long int n, long long int m, long long int p = 1000000007) { return ((n - m + p) % p + p) % p; } inline long long int modpro(long long int n, long long int m, long long int p = 1000000007) { return (((n % p) * (m % p)) % p + p) % p; } unsigned long long int powe(long long int first, long long int second) { unsigned long long int res = 1; while (second > 0) { if (second & 1) res = res * first; second = second >> 1; first = first * first; } return res; } long long int modpow(long long int first, long long int second, long long int p = 1000000007) { long long int res = 1; while (second > 0) { if (second & 1) res = modpro(res, first, p); second = second >> 1; first = modpro(first, first, p); } return res; } inline long long int modInverse(long long int n, long long int p = 1000000007) { if (n == 1) return 1; return modpow(n, p - 2, p); } inline long long int moddiv(long long int n, long long int m, long long int p = 1000000007) { return modpro(n, modInverse(m, p), p); } inline long long int modadd3(long long int first, long long int second, long long int z, long long int p = 1000000007) { return modadd(modadd(first, second, p), z, p); } inline long long int modadd4(long long int first, long long int second, long long int z, long long int w, long long int p = 1000000007) { return modadd(modadd(first, second, p), modadd(z, w, p), p); } inline long long int modnCr(long long int fac[], int n, int r, long long int p = 1000000007) { if (r == 0) return 1; return modpro(fac[n], modInverse(modpro(fac[r], fac[n - r], p), p), p); } template <typename T> inline T max3(T first, T second, T z) { return max(max(first, second), z); } template <typename T> inline T max4(T first, T second, T z, T w) { return max(max3(first, second, w), z); } template <typename T> inline T min3(T first, T second, T z) { return min(min(first, second), z); } template <typename T> inline T min4(T first, T second, T z, T w) { return min(min3(first, second, w), z); } template <typename T> void printArr(T *arr, int s, int n) { for (int i = s; i <= n; i++) { cout << arr[i] << " "; } cout << endl; } int a[200005]; set<pair<int, pair<int, int>>> ms; set<int> s2; int main() { std::ios::sync_with_stdio(false); cin.tie(NULL); int erer = 1; for (int erer2 = (1); erer2 < (erer + 1); erer2++) { int n; cin >> n; string s; cin >> s; int g = 0; for (int i = (0); i < (n); i++) if (s[i] == 'G') g++; for (int i = (0); i < (n); i++) s2.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') { ms.insert({abs(a[i + 1] - a[i]), {i, i + 1}}); } else if (s[i] == 'G' && s[i + 1] == 'B') { ms.insert({abs(a[i + 1] - a[i]), {i, i + 1}}); } } vector<pair<int, int>> ans; while (!ms.empty()) { auto u = *ms.begin(); ms.erase(ms.begin()); int l = u.second.first, r = u.second.second; if (!s2.count(l) || !s2.count(r)) continue; ans.push_back(u.second); s2.erase(l); s2.erase(r); if ((l - 1) >= 0 && (r + 1) < n) { auto it = s2.upper_bound(l - 1); auto it2 = s2.lower_bound(r + 1); if (it == s2.begin() || it2 == s2.end()) continue; it--; int first = *it, second = *it2; if ((s[first] == 'B' && s[second] == 'G') || (s[first] == 'G' && s[second] == 'B')) { ms.insert({abs(a[second] - a[first]), {first, second}}); } } } cout << ((long long int)(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 MAX_N = 200000; char s[MAX_N + 4]; int as[MAX_N], prvs[MAX_N], nxts[MAX_N]; bool used[MAX_N]; vector<pair<int, int> > ps; struct Stat { int d, i, j; Stat() {} Stat(int _d, int _i, int _j) : d(_d), i(_i), j(_j) {} bool operator<(const Stat &s) const { return d > s.d || (d == s.d && i > s.i); } }; int main() { int n; scanf("%d%s", &n, s); for (int i = 0; i < n; i++) scanf("%d", as + i); priority_queue<Stat> q; for (int i = 0, j = 1; j < n; i++, j++) { if (s[i] != s[j]) q.push(Stat(abs(as[j] - as[i]), i, j)); nxts[i] = j, prvs[j] = i; } prvs[0] = nxts[n - 1] = -1; while (!q.empty()) { Stat u = q.top(); q.pop(); if (used[u.i] || used[u.j]) continue; ps.push_back(pair<int, int>(u.i, u.j)); used[u.i] = used[u.j] = true; int i1 = prvs[u.i], j1 = nxts[u.j]; if (j1 >= 0) prvs[j1] = i1; if (i1 >= 0) nxts[i1] = j1; if (i1 >= 0 && j1 >= 0 && s[i1] != s[j1]) q.push(Stat(abs(as[j1] - as[i1]), i1, j1)); } printf("%d\n", (int)ps.size()); for (vector<pair<int, int> >::iterator vit = ps.begin(); vit != ps.end(); vit++) printf("%d %d\n", vit->first + 1, vit->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 Node { int a, i, j; Node(int a_, int i_, int j_) : a(a_), i(i_), j(j_) {} friend bool operator>(const Node& p, const Node& q) { if (p.a > q.a) return true; else if (p.a < q.a) return false; else if (p.i > q.i) return true; else return false; } }; const int SIZE = 210000; int a[SIZE], N[SIZE], P[SIZE], resi[SIZE], resj[SIZE]; char bg[SIZE]; priority_queue<Node, vector<Node>, greater<Node> > H; set<int> S; int main() { int n; cin >> n; cin >> bg; for (int i = 0; i < n; i++) { cin >> a[i]; N[i] = i + 1; P[i] = i - 1; } for (int i = 0; i < n - 1; i++) { if (bg[i] != bg[i + 1]) { H.push(Node(abs(a[i] - a[i + 1]), i, i + 1)); } } int p = 0; while (!H.empty()) { Node tmp = H.top(); H.pop(); if (S.find(tmp.i) != S.end() || S.find(tmp.j) != S.end()) continue; S.insert(tmp.i); S.insert(tmp.j); resi[p] = tmp.i + 1; resj[p++] = tmp.j + 1; int di = P[tmp.i], dj = N[tmp.j]; if (di >= 0) N[di] = dj; if (dj < n) P[dj] = di; if (di >= 0 && dj < n && bg[di] != bg[dj]) { H.push(Node(abs(a[di] - a[dj]), di, dj)); } } cout << p << endl; for (int i = 0; i < p; i++) { cout << resi[i] << ' ' << resj[i] << 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 = 1000 * 1000 * 1000; const long long INF = 1000ll * 1000ll * 1000ll * 1000ll * 1000ll * 1000ll; int n; vector<int> B, skill, L, R; int b, g; string buf; struct P { int x, y, dif; P() {} P(int a, int b, int c) { x = a; y = b; dif = c; } }; bool operator<(const P& a, const P& b) { return a.dif < b.dif || a.dif == b.dif && a.x < b.x; } set<P> S; int main() { g = 0, b = 0; cin >> n; cin >> buf; B.resize(n); L.resize(n); R.resize(n); skill.resize(n); for (int i = 0; i < n; ++i) { B[i] = buf[i] == 'B'; b += B[i]; L[i] = i - 1, R[i] = i + 1; } g = n - b; for (int i = 0; i < n; ++i) cin >> skill[i]; for (int i = 0; i < n - 1; ++i) { if (B[i] != B[i + 1]) { P add; add.x = i; add.y = i + 1; add.dif = abs(skill[i] - skill[i + 1]); S.insert(add); } } cout << min(g, b) << endl; for (int i = 0; i < min(g, b); ++i) { P cur = *S.begin(); cout << cur.x + 1 << " " << cur.y + 1 << endl; S.erase(cur); if (L[cur.x] != -1) { if (B[cur.x] != B[L[cur.x]]) S.erase(P(L[cur.x], cur.x, abs(skill[L[cur.x]] - skill[cur.x]))); R[L[cur.x]] = R[cur.y]; } if (R[cur.y] != n) { if (B[cur.y] != B[R[cur.y]]) S.erase(P(cur.y, R[cur.y], abs(skill[R[cur.y]] - skill[cur.y]))); L[R[cur.y]] = L[cur.x]; } if (L[cur.x] != -1 && R[cur.y] != n && B[L[cur.x]] != B[R[cur.y]]) S.insert(P(L[cur.x], R[cur.y], abs(skill[L[cur.x]] - skill[R[cur.y]]))); } 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 A { int l, r; }; int par[200005]; int p[200005]; int ne[200005]; int fnd(int x) { if (p[x] == x) return x; return p[x] = fnd(p[x]); } int fnd1(int x) { if (ne[x] == x) { return x; } return ne[x] = fnd1(ne[x]); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n; while (cin >> n) { char ch[200005]; for (int i = 1; i <= n; i++) { cin >> ch[i]; } vector<A> ans; long long arr[200005]; priority_queue<pair<long long, pair<int, int> >, vector<pair<long long, pair<int, int> > >, greater<pair<long long, pair<int, int> > > > pq; for (int i = 0; i <= n + 1; i++) { p[i] = i; ne[i] = i; } for (int i = 1; i <= n; i++) { cin >> arr[i]; } for (int i = 1; i < n; i++) { if (ch[i] != ch[i + 1]) { long long d = abs(arr[i] - arr[i + 1]); pq.push(make_pair(d, make_pair(i, i + 1))); } } static int vis[200005]; memset(vis, 0, sizeof vis); while (pq.size() > 0) { pair<long long, pair<int, int> > pp = pq.top(); pq.pop(); A a; a.l = pp.second.first; a.r = pp.second.second; if (vis[a.l] == 0 && vis[a.r] == 0) { vis[a.l] = 1; vis[a.r] = 1; ne[a.r] = fnd1(a.r + 1); ne[a.l] = fnd1(a.l + 1); p[a.l] = fnd(a.l - 1); p[a.r] = fnd(a.r - 1); ans.push_back(a); if (ne[a.r] <= n && p[a.l] > 0) { if (ch[ne[a.r]] != ch[p[a.l]]) { long long d = abs(arr[ne[a.r]] - arr[p[a.l]]); pq.push(make_pair(d, make_pair(p[a.l], ne[a.r]))); } } } } cout << ans.size() << endl; for (int i = 0; i < ans.size(); i++) { cout << ans[i].l << " " << ans[i].r << 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
//package school3; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; import java.util.TreeSet; public class C { Scanner in; PrintWriter out; // String INPUT = "4 BGBG 4 2 4 3"; // String INPUT = "4 BBGG 4 2 4 3"; // String INPUT = "4 BBGG 4 6 1 5"; // String INPUT = "4 BGBB 1 1 2 3"; String INPUT = ""; void solve() { int n = ni(); char[] bg = in.next().toCharArray(); int[] h = new int[n]; for(int i = 0;i < n;i++){ h[i] = ni(); } int[] next = new int[n]; int[] prev = new int[n]; for(int i = 0;i < n;i++){ next[i] = i + 1; prev[i] = i - 1; if(i == n - 1)next[i] = -1; // if(i == 0)prev[i] = -1; } final int[] hs = new int[n]; for(int i = 0;i < n - 1;i++){ hs[i] = Math.abs(h[i+1] - h[i]); } TreeSet<Integer> ts = new TreeSet<Integer>(new Comparator<Integer>(){ public int compare(Integer a, Integer b) { if(hs[a] != hs[b])return hs[a] - hs[b]; return a - b; } }); for(int i = 0;i < n - 1;i++){ if(bg[i] != bg[i+1])ts.add(i); } StringBuilder sb = new StringBuilder(); int ct = 0; while(ts.size() > 0){ int cur = ts.pollFirst(); sb.append((cur + 1) + " "); if(next[cur] == -1)throw new Error(); sb.append((next[cur] + 1) + "\n"); ct++; ts.remove(next[cur]); int p = prev[cur]; int x = next[cur] != -1 ? next[next[cur]] : -1; if(p != -1)next[p] = x; if(x != -1)prev[x] = p; if(x == -1){ ts.remove(p); } if(p != -1 && x != -1){ if(bg[p] != bg[x]){ ts.remove(p); hs[p] = Math.abs(h[x] - h[p]); ts.add(p); }else{ ts.remove(p); } } } out.println(ct); out.println(sb); } class Datum { public int hs; public int ind; public Datum(int hs, int ind) { this.hs = hs; this.ind = ind; } } void run() throws Exception { // int n = 200000; // StringBuilder sb = new StringBuilder(n + " "); // Random r = new Random(); // for(int i = 0;i < n;i++){ // sb.append(r.nextInt(2) == 0 ? 'B' : 'G'); // } // sb.append('\n'); // for(int i = 0;i < n;i++){ // sb.append(r.nextInt(1000000) + " "); // } // INPUT = sb.toString(); in = INPUT.isEmpty() ? new Scanner(System.in) : new Scanner(INPUT); out = new PrintWriter(System.out); solve(); out.flush(); } public static void main(String[] args) throws Exception { new C().run(); } int ni() { return Integer.parseInt(in.next()); } void tr(Object... o) { if(INPUT.length() != 0)System.out.println(o.length > 1 || o[0].getClass().isArray() ? Arrays.deepToString(o) : o[0]); } }
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 Pair { int u, v; }; int t[200000]; int aft[200000], bef[200000]; bool used[200000] = {false}; int abs(int i) { return i > 0 ? i : -i; } bool operator<(Pair i, Pair j) { if (abs(t[i.u] - t[i.v]) == abs(t[j.u] - t[j.v])) if (i.u == j.u) return i.v < j.v; else return i.u < j.u; else return abs(t[i.u] - t[i.v]) < abs(t[j.u] - t[j.v]); } set<Pair> s; int main() { int n; string str; Pair tmp; int ans = 0; cin >> n >> str; for (int i = 0; i < n; i++) cin >> t[i]; for (int i = 0; i < n; i++) { bef[i] = i - 1; aft[i] = i + 1; if (str[i] == 'G') ans++; } if (ans + ans > n) ans = n - ans; cout << ans << endl; for (int i = 0; i < n - 1; i = aft[i]) if (str[i] != str[aft[i]]) { tmp.u = i; tmp.v = aft[i]; s.insert(tmp); } while (!s.empty()) { tmp = *s.begin(); s.erase(s.begin()); if (used[tmp.u] || used[tmp.v]) continue; used[tmp.u] = used[tmp.v] = true; cout << tmp.u + 1 << ' ' << tmp.v + 1 << endl; aft[bef[tmp.u]] = aft[tmp.v]; bef[aft[tmp.v]] = bef[tmp.u]; if (bef[tmp.u] >= 0 && aft[tmp.v] < n && str[bef[tmp.u]] != str[aft[tmp.v]]) tmp.u = bef[tmp.u]; tmp.v = aft[tmp.v]; s.insert(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; const int MAXN = 1000 * 200 + 10; int a[MAXN]; bool boy[MAXN]; vector<pair<int, int> > ans; struct comp { const bool operator()(const pair<int, int>& x, const pair<int, int>& y) const { if (abs(a[x.first] - a[x.second]) == abs(a[y.first] - a[y.second])) return x.first < y.first; return abs(a[x.first] - a[x.second]) < abs(a[y.first] - a[y.second]); } }; set<pair<int, bool> > people; multiset<pair<int, int>, comp> mates; int main() { int n; cin >> n; for (int i = 0; i < n; i++) { char tmp; cin >> tmp; boy[i] = tmp == 'B'; people.insert(pair<int, bool>(i, boy[i])); } for (int i = 0; i < n; i++) { cin >> a[i]; if (i > 0 && boy[i] != boy[i - 1]) mates.insert(pair<int, int>(i - 1, i)); } while (!mates.empty()) { pair<int, int> cur = *mates.begin(); mates.erase(mates.begin()); ans.push_back(cur); set<pair<int, bool> >::iterator it = people.find(pair<int, bool>(cur.first, boy[cur.first])); if (it != people.begin()) { it--; pair<int, bool> x1 = *it; if (x1.second != boy[cur.first]) mates.erase(pair<int, int>(x1.first, cur.first)); it++; } it++; it++; if (it != people.end()) { pair<int, bool> x2 = *it; if (x2.second != boy[cur.second]) mates.erase(pair<int, int>(cur.second, x2.first)); } it--; it--; if (it != people.begin()) { it--; pair<int, bool> x1 = *it; it++; it++; it++; if (it != people.end()) { pair<int, bool> x2 = *it; if (x2.second != x1.second) mates.insert(pair<int, int>(x1.first, x2.first)); if (x2.second != boy[cur.second]) mates.erase(pair<int, int>(cur.second, x2.first)); } } people.erase(pair<int, bool>(cur.first, boy[cur.first])); people.erase(pair<int, bool>(cur.second, boy[cur.second])); } cout << ans.size() << endl; for (int 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
import java.io.*; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Comparator; import java.util.StringTokenizer; import java.util.TreeSet; /** * Created by IntelliJ IDEA. * User: piyushd * Date: 12/11/10 * Time: 2:59 PM * To change this template use File | Settings | File Templates. */ public class DancingLessons { private BufferedReader in; private PrintWriter out; private StringTokenizer st; int[] skill; boolean[] used; int[] left, right; int n; class Pair implements Comparable<Pair>{ public int first; public int second; public Pair(int a, int b){ first = a; second = b; } public int compareTo(Pair o) { if(Math.abs(skill[first] - skill[second]) != Math.abs(skill[o.first] - skill[o.second])) return (Math.abs(skill[first] - skill[second]) < Math.abs(skill[o.first] - skill[o.second])) ? -1 : 1; if(first != o.first) return (first < o.first) ? -1 : 1; return (second < o.second) ? -1 : 1; } } void solve() throws IOException { n = nextInt(); skill = new int[n]; left = new int[n]; right = new int[n]; used = new boolean[n]; String line = next(); for(int i = 0; i < n; i++) { skill[i] = nextInt(); left[i] = i - 1; right[i] = i + 1; } TreeSet<Pair> matches = new TreeSet<Pair>(); for(int i = 0; i < n - 1; i++) if(line.charAt(i) != line.charAt(i + 1)) matches.add(new Pair(i, i + 1)); ArrayList<Integer> list1 = new ArrayList<Integer>(); ArrayList<Integer> list2 = new ArrayList<Integer>(); int k = 0; while(!matches.isEmpty()){ Pair top = matches.pollFirst(); if(used[top.first] || used[top.second])continue; k++; used[top.first] = used[top.second] = true; list1.add(top.first + 1); list2.add(top.second + 1); int prev = left[top.first]; int next = right[top.second]; if(prev >= 0 && next < n){ left[next] = prev; right[prev] = next; if(line.charAt(prev) != line.charAt(next)) matches.add(new Pair(prev, next)); } } out.println(k); Integer[] first = new Integer[k]; Integer[] second = new Integer[k]; list1.toArray(first); list2.toArray(second); for(int i = 0; i < k; i++) out.println(first[i] + " " + second[i]); } DancingLessons() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); //in = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C://Users/piyushd/Desktop/codeforces/sample.txt")))); out = new PrintWriter(System.out); eat(""); solve(); in.close(); out.close(); } private void eat(String str) { st = new StringTokenizer(str); } String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } eat(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } public static void main(String[] args) throws IOException { new DancingLessons(); } }
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; template <typename T, typename TT> ostream &operator<<(ostream &s, pair<T, TT> t) { return s << "(" << t.first << "," << t.second << ")"; } template <typename T> ostream &operator<<(ostream &s, vector<T> t) { s << "{"; for (int i = 0; i < t.size(); i++) s << t[i] << (i == t.size() - 1 ? "" : ","); return s << "}" << endl; } char plec[200006]; int skill[200006]; set<int> ob; int main() { int n; scanf("%d", &(n)); ; scanf("%s", plec); for (int i = 0; i < n; i++) scanf("%d", &(skill[i])); ; for (int i = 0; i < n; i++) ob.insert(i); priority_queue<pair<int, pair<int, int> >, vector<pair<int, pair<int, int> > >, greater<pair<int, pair<int, int> > > > Q; for (int i = 0; i < n - 1; i++) { if (plec[i] != plec[i + 1]) { Q.push(make_pair(abs(skill[i] - skill[i + 1]), make_pair(i, i + 1))); } } vector<pair<int, int> > wyn; set<int>::iterator it; while (!Q.empty()) { pair<int, pair<int, int> > p = Q.top(); Q.pop(); pair<int, int> u = p.second; if (!((ob).find((u.first)) != (ob).end()) || !((ob).find((u.second)) != (ob).end())) continue; wyn.push_back(u); ob.erase(u.first); ob.erase(u.second); it = ob.lower_bound(u.second); if (it == ob.end()) continue; if (it == ob.begin()) continue; u.second = *it; it--; u.first = *it; if (plec[u.first] != plec[u.second]) { Q.push(make_pair(abs(skill[u.first] - skill[u.second]), u)); } } printf("%d\n", wyn.size()); for (typeof(wyn.begin()) i = wyn.begin(); i != wyn.end(); i++) printf("%d %d\n", (i->first) + 1, (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
#Again testing the condition of the server, code by Yijie Xia 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
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) 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) 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> int dr[] = {2, 2, -2, -2, 1, -1, 1, -1}; int dc[] = {1, -1, 1, -1, 2, 2, -2, -2}; int dr1[] = {0, 0, 0, 1, 1, 1, -1, -1, -1}; int dc1[] = {-1, 0, 1, -1, 0, 1, -1, 0, 1}; int dr2[] = {0, 0, 1, -1}; int dc2[] = {1, -1, 0, 0}; using namespace std; int main() { long long int n, i; while (cin >> n) { string t; cin >> t; long long int a[n + 5]; for (i = 0; i < n; i++) cin >> a[i]; priority_queue<pair<long long int, pair<long long int, long long int> > > pq; map<long long int, long long int> mp; vector<pair<long long int, long long int> > v; set<long long int> s; set<long long int>::iterator it, it1; for (i = 0; i < t.size(); i++) { s.insert(i); if (t[i] == 'G') { if (i > 0 && t[i - 1] == 'B') { long long int p = abs(a[i - 1] - a[i]); pq.push(make_pair(-p, make_pair(-i + 1, -i))); } if (i + 1 < t.size() && t[i + 1] == 'B') { long long int p = abs(a[i] - a[i + 1]); pq.push(make_pair(-p, make_pair(-i, -i - 1))); } } } while (pq.size() > 0) { long long int q = -pq.top().second.first; long long int r = -pq.top().second.second; pq.pop(); it = s.find(q); it1 = s.find(r); if ((*it) != q || (*it1) != r) continue; v.push_back(make_pair(q, r)); --it; it1++; long long int p = *it; long long int p1 = *it1; if (p >= 0 && p < q && p1 < t.size() && p1 > r) { if ((t[p] == 'B' && t[p1] == 'G') || (t[p] == 'G' && t[p1] == 'B')) { long long int rr = abs(a[p] - a[p1]); pq.push(make_pair(-rr, make_pair(-p, -p1))); } } s.erase(q); s.erase(r); } cout << v.size() << endl; for (i = 0; i < v.size(); i++) { cout << v[i].first + 1 << " " << v[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; vector<char> bg; vector<int> a; int main() { int n; cin >> n; bg.resize(n); a.resize(n); vector<int> next(n, -1); vector<int> prev(n, -1); int nG = 0, nB = 0; for (int i = 0; i < n; ++i) { cin >> bg[i]; bg[i] == 'B' ? ++nB : ++nG; } int k = min(nG, nB); for (int i = 0; i < n; ++i) cin >> a[i]; set<pair<int, int> > s; for (int i = 0; i < n - 1; ++i) { next[i] = i + 1; prev[i + 1] = i; if (bg[i] != bg[i + 1]) s.insert(pair<int, int>(abs(a[i] - a[i + 1]), i)); } cout << k << endl; for (int i = 0; i < k; ++i) { pair<int, int> p = *s.begin(); int A = p.second; int B = next[p.second]; cout << A + 1 << ' ' << B + 1 << endl; s.erase(s.begin()); int L = prev[A]; int R = next[B]; if (L != -1) { s.erase(pair<int, int>(abs(a[L] - a[A]), L)); next[L] = R; } if (R != -1) { s.erase(pair<int, int>(abs(a[R] - a[B]), B)); prev[R] = L; } if (L != -1 && R != -1 && bg[L] != bg[R]) s.insert(pair<int, int>(abs(a[R] - a[L]), L)); } 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.awt.geom.Line2D; import java.awt.geom.Point2D; import java.io.*; import java.math.BigInteger; import static java.math.BigInteger.*; import java.util.*; public class C1{ int[]h; char[]type; int[]prev; int[]next; int n; void solve()throws Exception { n=nextInt(); type=nextToken().toCharArray(); h=new int[n]; for(int i=0;i<n;i++) h[i]=nextInt(); next=new int[n]; prev=new int[n]; Arrays.fill(next, -1); Arrays.fill(prev, -1); for(int i=0;i<n;i++) { if(i>0) prev[i]=i-1; if(i+1<n) next[i]=i+1; } TreeSet<Integer>t=new TreeSet<Integer>(new Comparator<Integer>() { public int compare(Integer a,Integer b) { int z1; if(next[a]==-1 || type[a]==type[next[a]]) z1=Integer.MAX_VALUE; else z1=Math.abs(h[a]-h[next[a]]); int z2; if(next[b]==-1 || type[b]==type[next[b]]) z2=Integer.MAX_VALUE; else z2=Math.abs(h[b]-h[next[b]]); if(z1==z2) return a-b; else return z1-z2; } }); for(int i=0;i<n;i++) t.add(i); ArrayList<Integer>res=new ArrayList<Integer>(); while(t.size()>0) { int x=t.first(); int y=next[x]; if(y==-1 || type[x]==type[y]) break; res.add(x+1); res.add(y+1); int a=prev[x]; int b=next[y]; if(a!=-1) { t.remove(a); } if(b!=-1) t.remove(y); t.remove(x); if(a!=-1) { next[a]=b; } if(b!=-1) prev[b]=a; if(a!=-1 && b!=-1) t.add(a); } System.out.println(res.size()/2); for(int i=0;i<res.size();i+=2) System.out.println(res.get(i)+" "+res.get(i+1)); } BufferedReader reader; PrintWriter writer; StringTokenizer stk; void run()throws Exception { reader=new BufferedReader(new InputStreamReader(System.in)); stk=null; writer=new PrintWriter(System.out); solve(); reader.close(); writer.close(); } int nextInt()throws Exception { return Integer.parseInt(nextToken()); } long nextLong()throws Exception { return Long.parseLong(nextToken()); } double nextDouble()throws Exception { return Double.parseDouble(nextToken()); } String nextString()throws Exception { return nextToken(); } String nextLine()throws Exception { return reader.readLine(); } String nextToken()throws Exception { if(stk==null || !stk.hasMoreTokens()) { stk=new StringTokenizer(nextLine()); return nextToken(); } return stk.nextToken(); } public static void main(String[]args) throws Exception { new C1().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; const int maxn = 250000; bool vis[maxn]; int sk[maxn]; int ll[maxn], rr[maxn]; char s[maxn]; int n; struct node { int u, v, val; }; bool operator<(const node a, const node b) { if (a.val != b.val) return a.val > b.val; return a.u > b.u; } priority_queue<node> q; int main() { while (cin >> n) { node tmp; memset(s, 0, sizeof s); int num = 0; scanf("%s", s + 1); for (int i = 1; i <= n; i++) { ll[i] = i - 1; rr[i] = i + 1; if (s[i] == 'B') num += 1; } num = (num < n - num) ? num : n - num; for (int i = 1; i <= n; i++) scanf("%d", &sk[i]); while (!q.empty()) q.pop(); for (int i = 1; i < n; i++) { if (s[i] != s[i + 1]) { tmp.u = i; tmp.v = i + 1; tmp.val = abs(sk[i] - sk[i + 1]); q.push(tmp); } } memset(vis, 0, sizeof vis); printf("%d\n", num); while (num--) { while (!q.empty()) { tmp = q.top(); q.pop(); if (!vis[tmp.u] && !vis[tmp.v]) { printf("%d %d\n", tmp.u, tmp.v); vis[tmp.u] = 1; vis[tmp.v] = 1; break; } } int a = ll[tmp.u]; int b = rr[tmp.v]; rr[a] = b; ll[b] = a; tmp.u = a; tmp.v = b; tmp.val = abs(sk[a] - sk[b]); if (a > 0 && b <= n && s[a] != s[b]) q.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; const int MAXN = 200000 + 3; struct Node { int l, r, dif; Node(int _l = 0, int _r = 0, int _dif = 0) { l = _l, r = _r, dif = _dif; } bool operator<(const Node &a) const { if (a.dif == dif) return a.l < l; return a.dif < dif; } }; priority_queue<Node> que; int a[MAXN]; int is[MAXN]; int L[MAXN]; int R[MAXN]; int use[MAXN]; pair<int, int> ans[MAXN]; char ch[MAXN]; inline int fab(int x, int y) { if (x > y) return x - y; return y - x; } void solve(int n) { int tot = 0; for (int i = 1; i <= n; i++) { L[i] = i - 1; R[i] = i + 1; } while (!que.empty()) que.pop(); memset(use, 0, sizeof use); Node now; for (int i = 1; i < n; i++) { if (is[i] + is[i + 1] == 1) { now = Node(i, i + 1, fab(a[i], a[i + 1])); que.push(now); } } while (!que.empty()) { now = que.top(); que.pop(); if (!use[now.l] && !use[now.r]) { ans[tot++] = make_pair(now.l, now.r); use[now.l] = use[now.r] = 1; while (use[L[now.l]]) { L[now.l] = L[L[now.l]]; } L[now.r] = L[now.l]; while (use[R[now.r]]) { R[now.r] = R[R[now.r]]; } R[now.l] = R[now.r]; if (L[now.l] == 0 || R[now.r] == n + 1) continue; if (is[L[now.l]] + is[R[now.r]] != 1) continue; now = Node(L[now.l], R[now.r], fab(a[L[now.l]], a[R[now.r]])); que.push(now); } } printf("%d\n", tot); for (int i = 0; i < tot; i++) { printf("%d %d\n", ans[i].first, ans[i].second); } return; } int main() { int n; scanf("%d", &n); scanf("%s", ch + 1); memset(is, 0, sizeof is); for (int i = 1; i <= n; i++) { if (ch[i] == 'B') is[i] = 1; } for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); } solve(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; int n, lenans; int ans[200010][2]; int vis[200010], a[200010], l[200010], r[200010]; char s[200010]; struct point { int l, r, w; bool operator<(const point& b) const { return w == b.w ? l > b.l : w > b.w; } }; priority_queue<point> q; int main() { while (~scanf("%d", &n)) { scanf("%s", s); for (int i = 0; i < n; i++) { scanf("%d", a + i); l[i] = i - 1; r[i] = i + 1; } while (!q.empty()) q.pop(); point h; for (int i = 1; i < n; i++) { if (s[i] == 'B' && s[i - 1] == 'G' || s[i] == 'G' && s[i - 1] == 'B') { h.l = i - 1; h.r = i; h.w = abs(a[i] - a[i - 1]); q.push(h); } } lenans = 0; memset(vis, 0, sizeof(vis)); point x; while (!q.empty()) { x = q.top(); q.pop(); if (vis[x.l] == 1 || vis[x.r] == 1) { continue; } vis[x.l] = 1; vis[x.r] = 1; ans[lenans][0] = x.l; ans[lenans][1] = x.r; lenans++; r[l[x.l]] = r[x.r]; l[r[x.r]] = l[x.l]; x.l = l[x.l]; x.r = r[x.r]; if (x.l >= 0 && x.r < n) { if (s[x.l] == 'B' && s[x.r] == 'G' || s[x.r] == 'B' && s[x.l] == 'G') { h.l = x.l; h.r = x.r; h.w = abs(a[x.l] - a[x.r]); q.push(h); } } } printf("%d\n", lenans); for (int i = 0; i < lenans; i++) { printf("%d %d\n", ans[i][0] + 1, ans[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
import java.util.*; public class P045C { private static class Pair implements Comparable<Pair> { private int left; private int right; private int skillDiff; public Pair(int left, int right, int skillDiff) { this.left = left; this.right = right; this.skillDiff = skillDiff; } public int compareTo(Pair other) { if (skillDiff < other.skillDiff) return -1; if (skillDiff > other.skillDiff) return 1; return left - other.left; } } private int[] skill; private char[] gender; private boolean[] out; private int[] prev; private int[] next; private PriorityQueue<Pair> queue = new PriorityQueue<Pair>(); private int calcSkillDiff(int i, int j) { return Math.abs(skill[i] - skill[j]); } private void processPair(Pair pair) { int l = pair.left; int r = pair.right; if (out[l] || out[r]) return; if (prev[l] != l && next[r] != r) { next[prev[l]] = next[r]; prev[next[r]] = prev[l]; int l2 = prev[l]; int r2 = next[r]; if (gender[l2] != gender[r2]) { queue.add(new Pair(l2, r2, calcSkillDiff(l2, r2))); } } else if (next[r] != r) { prev[next[r]] = next[r]; } else if (prev[l] != l) { next[prev[l]] = prev[l]; } System.out.printf("%d %d\n", l+1, r+1); out[l] = out[r] = true; } private void solve() { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); skill = new int[n]; gender = new char[n]; out = new boolean[n]; prev = new int[n]; next = new int[n]; prev[0] = 0; next[0] = 1; prev[n-1] = n-2; next[n-1] = n-1; for (int i = 1; i <= n-2; i++) { prev[i] = i-1; next[i] = i+1; } String s = sc.next(); int numBoy = 0; for (int i = 0; i < n; i++) { gender[i] = s.charAt(i); if (gender[i] == 'B') numBoy++; } for (int i = 0; i < n; i++) { skill[i] = sc.nextInt(); } System.out.println(Math.min(numBoy, n-numBoy)); for (int i = 0; i < n-1; i++) { if (gender[i] != gender[i+1]) { queue.add(new Pair(i, i+1, calcSkillDiff(i, i+1))); } } while(!queue.isEmpty()) { Pair pair = queue.poll(); processPair(pair); } } public static void main(String[] args) { P045C solution = new P045C(); solution.solve(); } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal — as "and". Input The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(in, out); out.close(); } } class TaskD { private static final int N = 200000; private int left[] = new int[N]; private int right[] = new int[N]; private int val[] = new int[N]; private int sum[][] = new int[30][N]; private int add[][] = new int[30][N]; private int answer[] = new int[N]; private int MAX_BIT = 30; public void solve(InputReader in, OutputWriter out) { int n = in.nextInt(); int m = in.nextInt(); for (int i = 0; i < m; i++) { left[i] = in.nextInt() - 1; right[i] = in.nextInt() - 1; val[i] = in.nextInt(); for (int bit = 0; bit < MAX_BIT; bit++) { if(isBitSet(val[i], bit)) { add[bit][left[i]]++; add[bit][right[i]+1]--; } } } for (int bit = 0; bit < MAX_BIT; bit++) { int current = 0; for (int i = 0; i < n; i++) { current += add[bit][i]; sum[bit][i+1] = sum[bit][i] + (current > 0 ? 1 : 0); } } for (int i = 0; i < m; i++) { for (int bit = 0; bit < MAX_BIT; bit++) { if(!isBitSet(val[i], bit) && ((sum[bit][right[i]+1] - sum[bit][left[i]]) == (right[i] + 1 - left[i]))) { out.printLine("NO"); return; } } } out.printLine("YES"); for (int bit = 0; bit < MAX_BIT; bit++) { for (int i = 0; i < n; i++) { if(sum[bit][i+1] != sum[bit][i]) { answer[i] |= (1 << bit); } } } for (int i = 0; i < n; i++) { out.print(answer[i] + " "); } } private boolean isBitSet(int val, int bit) { return ((val >> bit) & 1) !=0; } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public boolean hasNext() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { String line = reader.readLine(); if (line == null) { return false; } tokenizer = new StringTokenizer(line); } catch (IOException e) { throw new RuntimeException(e); } } return true; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal — as "and". Input The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.util.*; import java.io.*; public class Main implements Runnable { int[] a; int[] sg; public void solve() throws IOException { int N = nextInt(), M = nextInt(); int[] r = new int[M]; int[] l = new int[M]; int[] v = new int[M]; for(int i = 0; i < M; i++){ l[i] = nextInt() - 1; r[i] = nextInt() - 1; v[i] = nextInt(); } a = new int[N]; for(int bit = 0; bit < 31; bit++){ int[] sum = new int[N+5]; for(int i = 0; i < M; i++) if((v[i] & (1 << bit)) > 0){ sum[l[i]]++; sum[r[i] + 1]--; } for(int i = 1; i <= N; i++) sum[i] += sum[i-1]; for(int i = 0; i < N; i++) if(sum[i] > 0) a[i] += (1 << bit); } sg = new int[4 * N]; buildSegmentTree(1, 0, N); //debug(sg); StringBuilder ans = new StringBuilder(); for(int i = 0; i < M; i++){ if(query(1, l[i], r[i] + 1, 0, N) != v[i]){ System.out.println("NO"); return; } } System.out.println("YES"); for(int i = 0; i < N; i++) ans.append(a[i] + " "); System.out.println(ans.toString()); } private void buildSegmentTree(int root, int start, int end){ if(start + 1 == end){ //System.err.println(root + " " + start); sg[root] = a[start]; return; } int mid = (start + end) >> 1; buildSegmentTree(root * 2, start, mid); buildSegmentTree(root * 2 + 1, mid, end); sg[root] = sg[root * 2] & sg[root * 2 + 1]; } private int query(int root, int l, int r, int L, int R){ if(l == L && r == R){ return sg[root]; } int ret = Integer.MAX_VALUE / 2; int mid = (L + R) >> 1; if(l < mid){ ret &= query(root * 2, l, Math.min(r, mid), L, mid); } if(r > mid){ ret &= query(root * 2 + 1, Math.max(mid, l) , r, mid, R); } return ret; } //----------------------------------------------------------- public static void main(String[] args) { new Main().run(); } public void debug(Object... arr){ System.out.println(Arrays.deepToString(arr)); } public void print1Int(int[] a){ for(int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); } public void print2Int(int[][] a){ for(int i = 0; i < a.length; i++){ for(int j = 0; j < a[0].length; j++){ System.out.print(a[i][j] + " "); } System.out.println(); } } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); tok = null; solve(); in.close(); } catch (IOException e) { System.exit(0); } } public String nextToken() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } BufferedReader in; StringTokenizer tok; }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal — as "and". Input The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
/* ID: govind.3, GhpS, govindpatel LANG: JAVA TASK: Main */ import java.io.*; import java.util.*; public class Main { private final int BIT = 30; private final int MAX = 1000 * 1000;//10^6 private int[] tree = new int[4 * MAX]; private int[] values = new int[MAX]; private void build(int v, int tl, int tr) {//v=1 => root, tl=0 => values.sIndex, tr=N-1 => values.length-1 if (tl == tr) { tree[v] = values[tl]; } else { int tm = (tl + tr) / 2; build(2 * v, tl, tm);//left build(2 * v + 1, tm + 1, tr);//right tree[v] = tree[v * 2] & tree[v * 2 + 1]; } } private int AND(int v, int tl, int tr, int l, int r) { int ans = (1 << BIT) - 1; if (l > r) { return ans; } if (l == tl && r == tr) { return tree[v]; } int tm = (tl + tr) / 2; ans = ans & AND(2 * v, tl, tm, l, Math.min(r, tm)); ans = ans & AND(2 * v + 1, tm + 1, tr, Math.max(l, tm + 1), r); return ans; } private void solve() throws IOException { StringBuilder sb = new StringBuilder(""); int N = nextInt(); int M = nextInt(); int[][] query = new int[M][]; int[] sum = new int[N + 1]; for (int i = 0; i < M; i++) { query[i] = new int[]{nextInt(), nextInt(), nextInt()};//(l,r) - q --query[i][0]; } for (int bit = 0; bit <= BIT; bit++) { Arrays.fill(sum, 0); for (int i = 0; i < M; i++) { if (((query[i][2] >> bit) & 1) != 0) { sum[query[i][0]]++; sum[query[i][1]]--; } } for (int i = 0; i < N; i++) { if (i > 0) { sum[i] += sum[i - 1]; } if (sum[i] > 0) {//set this bit; values[i] = values[i] | (1 << bit); } } } build(1, 0, N - 1); for (int i = 0; i < M; i++) { if (AND(1, 0, N - 1, query[i][0], query[i][1] - 1) != query[i][2]) { System.out.println("NO"); return; } } sb.append("YES\n"); for (int i = 0; i < N; i++) { sb.append(values[i]); if (i != N - 1) { sb.append(" "); } } System.out.println(sb); } public static void main(String[] args) { new Main().run(); } public void run() { try { in = new BufferedReader(new FileReader("Main.in")); out = new PrintWriter(new BufferedWriter(new FileWriter("Main.out"))); tok = null; solve(); in.close(); out.close(); System.exit(0); } catch (IOException e) {//(FileNotFoundException e) { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); tok = null; solve(); in.close(); out.close(); System.exit(0); } catch (IOException ex) { System.out.println(ex.getMessage()); System.exit(0); } } } private String nextToken() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } 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()); } BufferedReader in; StringTokenizer tok; PrintWriter out; }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal — as "and". Input The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class InterestingArray { static int[] a; static class SegmentTree { int [] tree; int N; public SegmentTree (int n){ N = n; tree = new int [N << 2]; build(1,0,N - 1); } private int left (int p){ return p << 1; } private int right (int p){ return (p << 1) + 1; } private void build (int p, int L, int R){ if(L == R){ tree[p] = a[L]; } else { int mid = (L + R) >> 1, left = left(p), right = right(p); build(left, L, mid); build(right, mid + 1, R); tree[p] = tree[left] & tree[right]; } } public int query (int i, int j){ return query(1, 0, N - 1, i, j); } private int query (int p, int L, int R, int i, int j){ if(i > R || j < L) return -1; if(L >= i && R <= j) return tree[p]; int mid = (L + R) >> 1, left = left(p), right = right(p); int ll = query(left, L, mid, i, j); int rr = query(right, mid + 1, R, i, j); if(ll == -1) return rr; if(rr == -1) return ll; return ll & rr; } } public static void main(String[] args) throws IOException { MyScanner sc = new MyScanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int m = sc.nextInt(); int [] l = new int [m]; int [] r = new int [m]; int [] q = new int [m]; for(int i = 0;i < m;i++){ l[i] = sc.nextInt() - 1; r[i] = sc.nextInt(); //exclusive q[i] = sc.nextInt(); } a = new int [n]; int [] bits = new int [n + 1]; for(int i = 0;i <= 30;i++){ Arrays.fill(bits, 0); for(int j = 0;j < m;j++){ if((q[j] & (1 << i)) != 0){ bits[l[j]]++; bits[r[j]]--; } } for(int j = 0;j < n;j++){ if(j > 0) bits[j] += bits[j - 1]; if(bits[j] > 0) a[j] |= (1 << i); } } // System.err.println(Arrays.toString(bits)); // System.err.println(Arrays.toString(a)); SegmentTree st = new SegmentTree(n); for(int i = 0;i < m;i++){ if(st.query(l[i], r[i] - 1) != q[i]){ System.out.println("NO"); return; } } System.out.println("YES"); StringBuilder sb = new StringBuilder(); for(int i = 0;i < n;i++) sb.append(a[i]).append(" "); System.out.println(sb.deleteCharAt(sb.length() - 1)); pw.close(); } static class MyScanner { StringTokenizer st; BufferedReader br; public MyScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public boolean ready() throws IOException { return br.ready(); } } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal — as "and". Input The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; const long long base = 1331; const long long N = 1e5 + 1; template <typename T> inline void Cin(T& x) { char c = getchar(); x = 0; while (c < '0' || c > '9') c = getchar(); while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar(); } template <typename T, typename... Args> inline void Cin(T& a, Args&... args) { Cin(a); Cin(args...); } long long s[N][31], n, m, a[N], l[N], r[N], q[N], res, ST[4 * N]; void build(long long id, long long l, long long r) { if (l == r) { ST[id] = a[l]; return; } long long mid = (l + r) / 2; build(id * 2, l, mid); build(id * 2 + 1, mid + 1, r); ST[id] = ST[id * 2] & ST[id * 2 + 1]; } void get(long long id, long long l, long long r, long long L, long long R) { if (L > r || R < l) { return; } if (L <= l && r <= R) { res = res & ST[id]; return; } long long mid = (l + r) / 2; get(id * 2, l, mid, L, R); get(id * 2 + 1, mid + 1, r, L, R); } void read(void) { cin >> n >> m; for (long long i = 1; i <= (long long)(m); ++i) { cin >> l[i] >> r[i] >> q[i]; for (long long j = 0; j < (long long)(31); ++j) { if (q[i] >> j & 1 == 1) { s[l[i]][j]++; s[r[i] + 1][j]--; } } } for (long long i = 1; i <= (long long)(n); ++i) { for (long long j = 0; j < (long long)(31); ++j) { s[i][j] += s[i - 1][j]; if (s[i][j] > 0) a[i] += (1 << j); } } build(1, 1, n); for (long long i = 1; i <= (long long)(m); ++i) { res = a[l[i]]; get(1, 1, n, l[i], r[i]); if (res != q[i]) { cout << "NO"; return; } } cout << "YES" << '\n'; for (long long i = 1; i <= (long long)(n); ++i) cout << a[i] << ' '; } signed main(void) { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); read(); }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal — as "and". Input The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class B { private static class Query implements Comparable<Query> { private final int left; private final int right; private final int value; private Query(int left, int right, int value) { this.left = left; this.right = right; this.value = value; } @Override public int compareTo(Query o) { return left == o.left ? right - o.right : left - o.left; } } private void solve() throws IOException { int n = nextInt(); int m = nextInt(); List<Query> queries = new ArrayList<>(); for (int i = 0; i < m; i++) { queries.add(new Query(nextInt() - 1, nextInt() - 1, nextInt())); } List<Integer>[] in = new List[n]; List<Integer>[] out = new List[n]; for (int i = 0; i < n; i++) { in[i] = new ArrayList<>(); out[i] = new ArrayList<>(); } for (Query query : queries) { in[query.left].add(query.value); out[query.right].add(query.value); } int[] a = new int[n]; int[] p = new int[30]; for (int i = 0; i < n; i++) { for (int x: in[i]) { for (int j = 0; j < 30; j++) { if ((x & (1 << j)) != 0) { p[j]++; } } } for (int j = 0; j < 30; j++) { if (p[j] > 0) { a[i] |= (1 << j); } } for (int x: out[i]) { for (int j = 0; j < 30; j++) { if ((x & (1 << j)) != 0) { p[j]--; } } } } int[] tree = new int[n * 4]; build(1, 0, n - 1, a, tree); for (Query query : queries) { if (get(1, 0, n - 1, query.left, query.right, tree) != query.value) { println("NO"); return; } } println("YES"); for (int i: a) { print(i + " "); } } private void build(int p, int l, int r, int[] a, int[] tree) { if (l == r) { tree[p] = a[l]; return; } int x = (l + r) / 2; build(p + p, l, x, a, tree); build(p + p + 1, x + 1, r, a, tree); tree[p] = tree[p + p] & tree[p + p + 1]; } private int get(int p, int l, int r, int L, int R, int[] tree) { if (l == L && r == R) { return tree[p]; } int x = (l + r) / 2; if (R <= x) { return get(p + p, l, x, L, R, tree); } else if (L > x) { return get(p + p + 1, x + 1, r, L, R, tree); } else { int left = get(p + p, l, x, L, x, tree); int right = get(p + p + 1, x + 1, r, x + 1, R, tree); return left & right; } } private String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } private int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } private double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private void print(Object o) { writer.print(o); } private void println(Object o) { writer.println(o); } private void printf(String format, Object... o) { writer.printf(format, o); } public static void main(String[] args) { long time = System.currentTimeMillis(); Locale.setDefault(Locale.US); new B().run(); System.err.printf("%.3f\n", 1e-3 * (System.currentTimeMillis() - time)); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; private void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (IOException e) { e.printStackTrace(); System.exit(13); } } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal — as "and". Input The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n, m; cin >> n >> m; map<int, vector<int> > open, close; vector<pair<pair<int, int>, int> > query(m); int a, b, c; for (int i = 0; i < m; ++i) { cin >> a >> b >> c; a--; b--; query[i].first.first = a; query[i].first.second = b; query[i].second = c; open[a].push_back(c); close[b].push_back(c); } vector<int> ans(n, 0); vector<int> mask(30, 0); int current = 0; for (int i = 0; i < n; ++i) { if (open.count(i)) { vector<int> &op = open[i]; for (int j = 0; j < op.size(); ++j) { int cur = op[j]; for (int k = 0; k < 30; ++k) { if ((cur >> k) & 1) mask[k]++; } } } for (int k = 0; k < 30; ++k) { if (mask[k] > 0) ans[i] |= (1 << k); } if (close.count(i)) { vector<int> &cl = close[i]; for (int j = 0; j < cl.size(); ++j) { int cur = cl[j]; for (int k = 0; k < 30; ++k) { if ((cur >> k) & 1) mask[k]--; } } } } int possible = 1; vector<vector<int> > ps(30, vector<int>(n, 0)); for (int k = 0; k < 30; ++k) if (((ans[0] >> k) & 1) == 0) ps[k][0] = 1; for (int k = 0; k < 30; ++k) { for (int i = 1; i < n; ++i) { if (((ans[i] >> k) & 1) == 0) ps[k][i] = 1; ps[k][i] += ps[k][i - 1]; } } for (int i = 0; i < m; ++i) { int x = query[i].first.first; int y = query[i].first.second; int z = query[i].second; int tmp = 0; for (int k = 0; k < 30; ++k) { int zero = ps[k][y]; if (x) zero -= ps[k][x - 1]; if (zero == 0) tmp |= (1 << k); } possible = possible and (tmp == z); } if (possible) { cout << "YES" << '\n'; for (int i = 0; i < n; ++i) { if (i) cout << " "; cout << ans[i]; } cout << '\n'; } else { cout << "NO" << '\n'; } return 0; }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal — as "and". Input The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; const int maxn = 100005; int cL, cR, W, b, n; struct Itree { int V[maxn * 4]; void pushdown(int o) { V[o * 2] |= V[o]; V[o * 2 + 1] |= V[o]; V[o] = 0; } void build(int o, int L, int R) { if (L == R) return; pushdown(o); int mid = (L + R) / 2; build(o * 2, L, mid); build(o * 2 + 1, mid + 1, R); V[o] = V[o * 2] & V[o * 2 + 1]; } void update(int o, int L, int R) { if (cL <= L && R <= cR) { V[o] |= W; return; } pushdown(o); int mid = (L + R) / 2; if (cL <= mid) update(o * 2, L, mid); if (cR > mid) update(o * 2 + 1, mid + 1, R); } void query(int o, int L, int R) { if (cL <= L && R <= cR) { if (b == 0) W = V[o]; else W = W & V[o]; b = 1; return; } int mid = (L + R) / 2; if (cL <= mid) query(o * 2, L, mid); if (cR > mid) query(o * 2 + 1, mid + 1, R); } void print(int o, int L, int R) { if (L == R) { printf("%d%c", V[o], L == n ? '\n' : ' '); return; } int mid = (L + R) / 2; print(o * 2, L, mid); print(o * 2 + 1, mid + 1, R); } } T; int LL[maxn], RR[maxn], QQ[maxn]; int main() { int m; while (scanf("%d%d", &n, &m) == 2) { memset(T.V, 0, sizeof(T.V)); for (int i = 0; i < m; ++i) { scanf("%d%d%d", &LL[i], &RR[i], &QQ[i]); cL = LL[i]; cR = RR[i]; W = QQ[i]; T.update(1, 1, n); } bool falg = true; T.build(1, 1, n); for (int i = 0; i < m; ++i) { b = 0; cL = LL[i]; cR = RR[i]; T.query(1, 1, n); if (QQ[i] != W) { falg = false; break; } } if (falg == false) { printf("NO\n"); } else { printf("YES\n"); T.print(1, 1, n); } } return 0; }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal — as "and". Input The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; const int MAX_N = 1 << 17; struct Node { int l, r, join, meet; }; Node T[2 * MAX_N]; void update(int l, int r, int q, int i = 1) { if (r <= T[i].l || l >= T[i].r) return; if (l <= T[i].l && r >= T[i].r) { T[i].meet |= q; return; } update(l, r, q, 2 * i); update(l, r, q, 2 * i + 1); } int query(int l, int r, int i = 1) { if (r <= T[i].l || l >= T[i].r) return ~0; if (l <= T[i].l && r >= T[i].r) { return T[i].join; } return query(l, r, 2 * i) & query(l, r, 2 * i + 1); } struct Query { int l, r, q; }; Query Q[MAX_N]; int main() { int N, M; cin >> N >> M; for (int i = MAX_N; i < 2 * MAX_N; ++i) { T[i].l = i - MAX_N; T[i].r = T[i].l + 1; } for (int i = MAX_N - 1; i > 0; --i) { T[i].l = T[2 * i].l; T[i].r = T[2 * i + 1].r; } for (int i = 0; i < M; ++i) { cin >> Q[i].l >> Q[i].r >> Q[i].q; --Q[i].l; update(Q[i].l, Q[i].r, Q[i].q); } for (int i = MAX_N; i < 2 * MAX_N; ++i) { T[i].join = i < MAX_N + N ? T[i].meet : ~0; for (int j = i >> 1; j > 0; j >>= 1) { T[i].join |= T[j].meet; } } for (int i = MAX_N - 1; i > 0; --i) { T[i].join = T[2 * i].join & T[2 * i + 1].join; } int i; for (i = 0; i < M; ++i) { if (query(Q[i].l, Q[i].r) != Q[i].q) break; } if (i == M) { cout << "YES\n"; cout << T[MAX_N].join; for (int i = MAX_N + 1; i < MAX_N + N; ++i) { cout << " " << T[i].join; } cout << "\n"; } else { cout << "NO\n"; } return 0; }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal — as "and". Input The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; int k[30][100002]; void die() { printf("NO"); exit(0); } int l[100001], r[100001], v[100001], ans[100000]; int main() { int n, m, i, j, a, b, c; scanf("%d%d", &n, &m); for (i = 0; i < m; i++) scanf("%d%d%d", l + i, r + i, v + i); for (i = 0; i < m; i++) { for (j = 0; j < 30; j++) { int t = (v[i] >> j) & 1; if (t) k[j][l[i]]++, k[j][r[i] + 1]--; } } for (i = 1; i <= n; i++) for (j = 0; j < 30; j++) k[j][i] += k[j][i - 1]; for (i = 1; i <= n; i++) for (j = 0; j < 30; j++) if (k[j][i]) k[j][i] = 1; for (i = 1; i <= n; i++) for (j = 0; j < 30; j++) k[j][i] += k[j][i - 1]; int diff; for (i = 0; i < m; i++) { for (j = 0; j < 30; j++) { int t = (v[i] >> j) & 1; if (!t && k[j][r[i]] - k[j][l[i] - 1] == r[i] - l[i] + 1) die(); } } for (i = 0; i < n; i++) for (j = 0; j < 30; j++) ans[i] |= (k[j][i + 1] - k[j][i]) << j; printf("YES\n"); for (i = 0; i < n; i++) printf("%d ", ans[i]); }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal — as "and". Input The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; const int INF = 2000000000; const int N = 1e5 + 5; const int TN = 1 << 18; const double PI = acos(-1); int n, m, k; long long tree[TN], lazy[TN] = {0}; void probagate(int l, int r, int p) { tree[p] |= lazy[p]; if (l != r) { lazy[p << 1] |= lazy[p]; lazy[(p << 1) | 1] |= lazy[p]; } lazy[p] = 0; } void update(int val, int ql, int qr, int l = 0, int r = n - 1, int p = 1) { probagate(l, r, p); if (ql > r || qr < l) return; if (ql <= l && r <= qr) { lazy[p] |= val; probagate(l, r, p); return; } int m = (l + r) >> 1; update(val, ql, qr, l, m, (p << 1)); update(val, ql, qr, m + 1, r, (p << 1) | 1); tree[p] = tree[(p << 1)] & tree[(p << 1) | 1]; } int get(int ql, int qr, int l = 0, int r = n - 1, int p = 1) { probagate(l, r, p); if (ql > r || qr < l) return (1LL << 31) - 1; if (ql <= l && r <= qr) { return tree[p]; } int m = (l + r) >> 1; return get(ql, qr, l, m, (p << 1)) & get(ql, qr, m + 1, r, (p << 1) | 1); } void print(int l = 0, int r = n - 1, int p = 1) { probagate(l, r, p); if (l == r) { printf("%d ", tree[p]); return; } int m = (l + r) >> 1; print(l, m, (p << 1)); print(m + 1, r, (p << 1) | 1); } int main() { scanf("%d%d", &n, &m); vector<pair<pair<int, int>, int>> v; for (int i = 0; i < m; i++) { int a, b, c; scanf("%d%d%d", &a, &b, &c); a--; b--; v.push_back({{a, b}, c}); update(c, a, b); } for (int i = 0; i < m; i++) { int a = v[i].first.first; int b = v[i].first.second; int c = v[i].second; if (get(a, b) != c) { return puts("NO"); } } puts("YES"); print(); }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal — as "and". Input The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
/* If you want to aim high, aim high Don't let that studying and grades consume you Just live life young ****************************** If I'm the sun, you're the moon Because when I go up, you go down ******************************* I'm working for the day I will surpass you https://www.a2oj.com/Ladder16.html */ import java.util.*; import java.io.*; import java.math.*; public class x482B { public static void main(String omkar[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); int M = Integer.parseInt(st.nextToken()); StringBuilder sb = new StringBuilder(); Range[] ranges = new Range[M]; for(int i=0; i < M; i++) { st = new StringTokenizer(infile.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); int c = Integer.parseInt(st.nextToken()); ranges[i] = new Range(a,b,c); } int[][] cnt = new int[N][30]; for(Range r: ranges) for(int b=0; b < 30; b++) if((r.val&(1<<b)) > 0) { cnt[r.left][b]++; if(r.right+1 < N) cnt[r.right+1][b]--; } int[] res = new int[N]; for(int b=0; b < 30; b++) { int val = 0; for(int i=0; i < N; i++) { val += cnt[i][b]; if(val > 0) res[i] += (1 << b); } } SegmentTree tree = new SegmentTree(0, N+1); for(int i=0; i < N; i++) tree.update(i, res[i]); for(Range r: ranges) if(tree.query(r.left, r.right) != r.val) { System.out.println("NO"); return; } System.out.println("YES"); for(int x: res) sb.append(x+" "); System.out.println(sb); } } class Range { public int left; public int right; public int val; public Range(int a, int b, int c) { left = a-1; right = b-1; val = c; } } class SegmentTree { //range query, non lazy final int[] val; final int treeFrom; final int length; public SegmentTree(int treeFrom, int treeTo) { this.treeFrom = treeFrom; int length = treeTo - treeFrom + 1; int l; for (l = 0; (1 << l) < length; l++); val = new int[1 << (l + 1)]; this.length = 1 << l; } public void update(int index, int delta) { //replaces value int node = index - treeFrom + length; val[node] = delta; for (node >>= 1; node > 0; node >>= 1) val[node] = comb(val[node << 1], val[(node << 1) + 1]); } public int query(int from, int to) { //inclusive bounds if (to < from) return 0; //0 or 1? from += length - treeFrom; to += length - treeFrom + 1; //0 or 1? int res = (1 << 30)-1; for (; from + (from & -from) <= to; from += from & -from) res = comb(res, val[from / (from & -from)]); for (; to - (to & -to) >= from; to -= to & -to) res = comb(res, val[(to - (to & -to)) / (to & -to)]); return res; } public int comb(int a, int b) { //change this return a&b; } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal — as "and". Input The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; inline void pisz(int n) { printf("%d\n", n); } template <typename T, typename TT> ostream& operator<<(ostream& s, pair<T, TT> t) { return s << "(" << t.first << "," << t.second << ")"; } template <typename T> ostream& operator<<(ostream& s, vector<T> t) { for (int(i) = 0; (i) < (((int)((t).size()))); ++(i)) s << t[i] << " "; return s; } const int all = (1 << 30) - 1; struct MinTree { int *el, s; MinTree(int h) { el = new int[2 * (s = 1 << h)]; for (int(x) = 0; (x) < (2 * s); ++(x)) el[x] = all; } void Set(int p, int v) { for (p += s, el[p] = v, p /= 2; p > 0; p /= 2) el[p] = el[2 * p] & el[2 * p + 1]; } int Find(int p, int k) { int m = all; p += s; k += s; while (p < k) { if (p & 1) { m = m & el[p]; ++p; } if (!(k & 1)) { m = m & el[k]; --k; } p /= 2; k /= 2; } if (p == k) m &= el[p]; return m; } }; vector<int> addAt[100007], delAt[100007]; int l[100007], r[100007], q[100007], val[100007]; int main() { int(n), (m); scanf("%d %d", &(n), &(m)); for (int(i) = 0; (i) < (m); ++(i)) scanf("%d %d %d", l + i, r + i, q + i); for (int(j) = 0; (j) < (m); ++(j)) { addAt[l[j]].push_back(q[j]); delAt[r[j] + 1].push_back(q[j]); } vector<int> cnt(32, 0); for (int(i) = 1; (i) <= (n); ++(i)) { for (__typeof(addAt[i].begin()) it = addAt[i].begin(); it != addAt[i].end(); it++) { for (int(b) = 0; (b) < (30); ++(b)) if ((*it) & (1 << b)) ++cnt[b]; } for (__typeof(delAt[i].begin()) it = delAt[i].begin(); it != delAt[i].end(); it++) { for (int(b) = 0; (b) < (30); ++(b)) if ((*it) & (1 << b)) --cnt[b]; } for (int(b) = 0; (b) < (30); ++(b)) if (cnt[b]) val[i] += 1 << b; } MinTree tr(17); for (int(i) = 1; (i) <= (n); ++(i)) tr.Set(i, val[i]); for (int(j) = 0; (j) < (m); ++(j)) if (tr.Find(l[j], r[j]) != q[j]) { printf("NO"); return 0; } printf("YES\n"); for (int(i) = 1; (i) <= (n); ++(i)) printf("%d ", val[i]); }
CPP