fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. template<typename X, typename Y>
  5. bool chmax(X& a, Y b) { return (a < b) ? a = b, 1 : 0; }
  6.  
  7. template<typename X, typename Y>
  8. bool chmin(X& a, Y b) { return (a > b) ? a = b, 1 : 0; }
  9.  
  10. using ll = long long;
  11. using pii = pair<int, int>;
  12.  
  13. const int N = 1e4+5;
  14.  
  15. int n, d[N];
  16.  
  17. void solve() {
  18. cin >> n;
  19. vector<pii> nodes;
  20. for (int i = 1; i <= n; i++) {
  21. cin >> d[i];
  22. nodes.push_back({d[i], i});
  23. }
  24. sort(nodes.begin(), nodes.end(), greater<pii>());
  25. vector<pii> edges;
  26. vector<int> connected;
  27. vector<vector<bool>> adj(n + 5, vector<bool>(n + 5, false));
  28. connected.push_back(nodes[0].second);
  29. int j = 0;
  30. for (int i = 1; i < n; i++) {
  31. int v = nodes[i].second;
  32. while (j < (int)connected.size() && d[connected[j]] == 0) j++;
  33. int u = connected[j];
  34. edges.push_back({u, v});
  35. adj[u][v] = adj[v][u] = true;
  36. d[u]--; d[v]--;
  37. connected.push_back(v);
  38. }
  39. priority_queue<pii> pq;
  40. for (int i = 1; i <= n; i++)
  41. if (d[i] > 0) pq.push({d[i], i});
  42. while (!pq.empty()) {
  43. auto [d_u, u] = pq.top(); pq.pop();
  44. if (d_u != d[u]) continue;
  45. nodes.clear();
  46. while (d[u] > 0 && !pq.empty()) {
  47. auto [d_v, v] = pq.top(); pq.pop();
  48. if (d_v != d[v]) continue;
  49. if (!adj[u][v]) {
  50. edges.push_back({u, v});
  51. adj[u][v] = adj[v][u] = true;
  52. d[u]--; d[v]--;
  53. }
  54. if (d[v] > 0) nodes.push_back({d[v], v});
  55. }
  56. for (pii p : nodes) pq.push(p);
  57. }
  58. for (pii e : edges) cout << e.first << ' ' << e.second << '\n';
  59. }
  60.  
  61. int main() {
  62. ios_base::sync_with_stdio(false); cin.tie(NULL);
  63.  
  64. #define TASK "MKGRAPH"
  65. if (fopen(TASK".INP", "r")) {
  66. freopen(TASK".INP", "r", stdin);
  67. freopen(TASK".OUT", "w", stdout);
  68. }
  69.  
  70. int tests = 1; // cin >> tests;
  71. while (tests--) solve();
  72.  
  73. #ifdef LOCAL
  74. cerr << "\nTime elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
  75. #endif
  76. return 0;
  77. }
  78.  
Success #stdin #stdout 0.01s 5316KB
stdin
3
2 2 2
stdout
3 2
3 1
2 1