Topic links: codeforces the Maximum-1082D a Diameter Graph
The meaning of problems
There are n points, the i-th point of maximum degree $ $ a_i, seeking to make the composition of FIG communication scheme largest diameter.
Thinking
Determining whether a connected graph can be constructed, if possible, all points greater than 1 degree together into one line, and the rest of it is even possible at the leftmost and rightmost points, and even then can easily, so it must be greedy optimal.
Implementation code
1 #include <cstdio> 2 const int maxn = 510; 3 struct Node 4 { 5 int deg, idx; 6 } no[maxn]; 7 struct Edge 8 { 9 int u, v; 10 } ed[maxn]; 11 int no1[maxn]; 12 13 int main() { 14 int n; 15 while (~scanf("%d", &n)) { 16 int cnt = 0, cnt1 = 0, tot = 0, sum = 0, ai; 17 for (int i = 1; i <= n; i++) { 18 scanf("%d", &ai); 19 sum += ai; 20 if (ai > 1) no[cnt++] = {ai, i}; 21 else no1[cnt1++] = i; 22 } 23 if (sum < (n - 1) * 2) { 24 puts("NO"); 25 continue; 26 } 27 int ans1 = 0, ans2 = 0; 28 for (int i = 0; i < cnt - 1; i++) { 29 ed[ans2++] = {no[i].idx, no[i+1].idx}; 30 no[i].deg--, no[i+1].deg--; 31 ans1++; 32 } 33 if (cnt1) { 34 d [ANS2 ++] = {No1 [cnt1- 1 ], in [ 0 ]} .idx; 35 in [ 0 ] .deg-- ; 36 ANS1 ++ ; 37 cnt1-- ; 38 } 39 if (cm -1) { 40 d [ANS2 ++] = {No1 [cnt1- 1 ], in [cm -1 ]} .idx; 41 in [cnt- 1 ] .deg-- ; 42 ANS1 ++ ; 43 cnt1-- ; 44 } 45 while (cnt1) { 46 for (int i = 0; i < cnt; i++) { 47 if (no[i].deg) { 48 ed[ans2++] = {no[i].idx, no1[cnt1-1]}; 49 no[i].deg--; 50 cnt1--; 51 } 52 if (cnt1 == 0) break; 53 } 54 } 55 printf("YES %d\n", ans1); 56 printf("%d\n", ans2); 57 for (int i = 0; i < ans2; i++) printf("%d %d\n", ed[i].u, ed[i].v); 58 } 59 return 0; 60 }