File size: 126,029 Bytes
08c8a6d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 |
AN INTRODUCTION TO THE USA COMPUTING OLYMPIAD Darren Yao 2020 R (cid:140) (cid:135) Java Edition Foreword This book was written as a comprehensive and up-to-date training resource for the USA Computing Olympiad. The goal was to create an “Art of Problem Solving” of sorts for the USACO: a one-stop-shop guide to prepare competitive programmers for the Bronze and Silver divisions of the USACO contests. My primary motivation for writing this book was the struggle to find the right resources when I first started doing USACO contests. When I eventually reached the Platinum division, new competitors often asked me for help in structuring their competitive programming practice. Since I always found myself explaining that the USACO lacked comprehensive training resources, I decided to write this book. I would like to thank a number of people for their contributions to this book. In particular, Michael Cao for writing sections 10.6 and 10.7 and helping with content revisions, Jason Chen for writing section 14.2 and extensive help with both content and LaTeX formatting, and Aaryan Prakash, Rishab Parthasarathy, Kevin Wang, and Stephanie Wu for their valuable and constructive feedback on early draft versions of the book. I’d also like to thank the USACO discord community for supporting me through my competitive programming journey; it was because of them that my competitive programming successes, and this book, are possible. Cover design by Dylan Yu. Author’s Profile Darren Yao is a USACO Platinum competitor. You can find his website at https: //darrenyao.com/. Copyright c(cid:13)2020 by Darren Yao All rights reserved. No part of this book may be reproduced or used in any manner without the prior written permission from the copyright owner. i Contents I Basic Techniques 1 The Beginning 1.1 Competitive Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.2 Contests and Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.3 Competitive Programming Practice . . . . . . . . . . . . . . . . . . . . . . . 1.4 About This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 Elementary Techniques 2.1 Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.2 Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Time/Space Complexity and Algorithm Analysis 3.1 Big O Notation and Complexity Calculations . . . . . . . . . . . . . . . . . . 3.2 Common Complexities and Constraints . . . . . . . . . . . . . . . . . . . . . 4 Built-in Data Structures 4.1 Dynamic Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.2 Stacks and the Various Types of Queues . . . . . . . . . . . . . . . . . . . . 4.3 Sets and Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.4 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . II Bronze 5 Simulation 5.1 Example 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.2 Example 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.3 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 Complete Search 6.1 Example 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.2 Generating Permutations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.3 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 2 2 3 3 4 5 5 9 10 10 11 13 13 14 16 19 20 21 21 22 23 24 24 26 27 ii CONTENTS 7 Additional Bronze Topics 7.1 Square and Rectangle Geometry . . . . . . . . . . . . . . . . . . . . . . . . . 7.2 Ad-hoc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.3 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . III Silver 8 Sorting and comparators 8.1 Comparators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.2 Sorting by Multiple Criteria . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.3 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Greedy Algorithms Introductory Example: Studying Algorithms . . . . . . . . . . . . . . . . . . 9.1 9.2 Example: The Scheduling Problem . . . . . . . . . . . . . . . . . . . . . . . 9.3 Failure Cases of Greedy Algorithms . . . . . . . . . . . . . . . . . . . . . . . 9.4 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Graph Theory 10.1 Graph Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.2 Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.3 Graph Representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.4 Graph Traversal Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.5 Floodfill . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.6 Disjoint-Set Data Structure 10.7 Bipartite Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.8 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Prefix Sums 11.1 Prefix Sums . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 Two Dimensional Prefix Sums . . . . . . . . . . . . . . . . . . . . . . . . . . 11.3 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Binary Search 12.1 Binary Search on the Answer . . . . . . . . . . . . . . . . . . . . . . . . . . 12.2 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12.3 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 Elementary Number Theory 13.1 Prime Factorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13.2 GCD and LCM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13.3 Modular Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13.4 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iii 28 28 28 29 31 32 32 34 34 36 36 37 38 39 40 40 41 42 47 51 54 57 58 60 60 61 63 64 64 65 66 68 68 69 70 70 CONTENTS 14 Additional Silver Topics 14.1 Two Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.2 Line Sweep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.3 Bitwise Operations and Subsets . . . . . . . . . . . . . . . . . . . . . . . . . 14.4 Ad-hoc Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.5 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . IV Problem Set 15 Parting Shots iv 71 71 73 75 78 78 80 81 Part I Basic Techniques 1 Chapter 1 The Beginning 1.1 Competitive Programming Welcome to the world of competitive programming! If you’ve had some basic programming experience with Java (perhaps at the level of an introductory course like AP Computer Science A), and are interested in competitive programming, then this book is for you. (If your primary language is C++, we also have a C++ edition of this book; please refer to that instead). If you currently do not know how to code, there are numerous resources available online to help you learn. This book aims to guide you through your competitive programming journey by providing a framework in which to learn the important contest topics. From competitive programming, not only do you improve at programming, but you improve your problem-solving skills which will help you in other areas. If at any point you have questions, feedback, or notice any mistakes, please contact me at darren.yao@gmail.com. Best of luck, and enjoy the ride! The goal of competitive programming is to write code to solve given problems quickly. These problems are not open problems; they are problems that are designed to be solved in the short timeframe of a contest, and have already been solved by the problem writer and testers. In general, each problem in competitive programming is solved by a two-step process: coming up with the algorithm, and then implementing it into working code. The degree of mathematics knowledge varies from contest to contest, but generally the level of mathematics required is relatively elementary, and we will review important topics in this book. A contest generally lasts for several hours, and consists of a set of problems. For each problem, when you complete your code, you submit it to a grader, which checks the answers calculated by the your program against a set of predetermined test cases. For each problem, you are given a time limit and a memory limit that your program must satisfy. Grading varies between contests; sometimes there is partial credit for passing some cases, while other times grading is all-or-nothing. For those of you with experience in software development, note that competitive programming is quite different, as the goal is to write programs that compute the correct answer, run quickly, and can be implemented quickly. Note that nowhere was maintainability of code mentioned. This means that you should throw away everything you know about traditional code writing; you don’t need to bother documenting your code, because it only needs to be readable to you, during the contest. 2 CHAPTER 1. THE BEGINNING 3 1.2 Contests and Resources The USA Computing Olympiad is a national programming competition that occurs four times a year, with December, January, February, and US Open contests. The regular contests are four hours long, and the US Open is five hours long. Each contest contains three problems. Solutions are evaluated and scored against a set of predetermined test cases that are not visible to the student. Scoring is out of 1000 points, with each problem being weighted equally. There are four divisions of contests: Bronze, Silver, Gold, and Platinum. After each contest, students who meet the contest-dependent cutoff for promotion will compete in the next division for future contests. While this book is primarily focused on the USACO, CodeForces is another contest programming platform that many students use for practice. CodeForces holds 2-hour contests very frequently, which are more focused on fast solving compared to USACO. However, we do think CodeForces is a valuable training platform, so many exercises and problems will come from there. We encourage you to create a CodeForces account and solve the provided problems there. CodeForces submissions are all-or-nothing; unlike USACO, there is no partial credit and you only receive credit for a problem if you pass all of the test cases. We will also include some exercises from Antti Laaksonen’s website CSES. It contains a selection of standard problems that you can use to learn and practice well-known algorithms and techniques. You should note that CSES’s grader is very slow, so don’t worry if you encounter a Time Limit Exceeded verdict; as long as you pass the majority of test cases within the time limit, and your time complexity is reasonable, you can consider the problem solved, and move on. 1.3 Competitive Programming Practice Reaching a high level in competitive programming requires dedication and motivation. For many people, their practice is inefficient because they do problems that are too easy, too hard, or simply of the wrong type. This book aims to correct that by providing comprehensive problem sets for each topic covered on the USA Computing Olympiad, as well as an extensive selection of problems across all topics in the final chapter. In the lower divisions, most problems use relatively elementary algorithms; the main challenge is deciding which algorithm to use, and implementing it correctly. In a contest, you should spend the bulk of your time thinking about the problem and coming up with the algorithm, rather than typing code. Thus, you should practice your implementation skills, so that during the contest, you can implement the algorithm quickly and correctly, without resorting to debugging. On Exercises and Practice Problems You improve at competitive programming by solving problems, so we strongly recommend that you make use of the included exercises in each section before moving on. Some of the problems will be easy, and some of them will be hard. This is because problems that you practice with should be of the appropriate difficulty. You don’t necessarily need to complete all the exercises at the end of each chapter, just do what you think is right for you. A CHAPTER 1. THE BEGINNING 4 problem at the right level of difficulty should be one of two types: either you struggle with the problem for a while before coming up with a working solution, or you miss it slightly and need to consult the solution for some small part. If you instantly come up with the solution, a problem is likely too easy, and if you’re missing multiple steps, it might be too hard. In general, especially on harder problems, I think it’s fine to read the solution relatively early on, as long as you’re made several different attempts at it and you can learn effectively from the solution. • On a bronze problem, read the solution after 15-20 minutes of no meaningful progress, after you’ve exhausted every idea you can think of. • On a silver problem, read the solution after 30-40 minutes of no meaningful progress. When you get stuck and consult the solution, you should not read the entire solution at once, and you certainly shouldn’t look at the solution code. Instead, it’s better to read the solution step by step until you get unstuck, at which point you should go back and finish the problem, and implement it yourself. Reading the full solution or its code should be seen as a last resort. IDEs and Text Editors Here’s some IDEs and text editors often used by competitive programmers: • Java: Visual Studio Code or IntelliJ/Eclipse • C++: Visual Studio Code, CodeBlocks, vim/gvim, Sublime Text. • Do not use online IDEs that display your code publicly, like the free version of ideone. This allows other users to copy your code, and you may get flagged for cheating. 1.4 About This Book This book aims to prepare students for the Bronze and Silver division of the USACO, with the goal of qualifying for Gold. We will do this by covering all the necessary algorithms, data structures, and skills to pass the Bronze and Silver contests. Many examples and practice problems have been provided; these are the most important part of studying competitive programming, so make sure you pay careful attention to the examples and solve the practice problems, which usually come from previous USACO contests. This book is intended for those who have some programming experience – Basic knowledge of Java at the level of an introductory class like AP Computer Science is expected. This book begins with some necessary background knowledge, which is then followed by lessons on common topics that appear on the Bronze and Silver divisions of USACO, and then examples. At the end of each chapter will be a set of problems from USACO, CodeForces, and CSES, where you can practice what you’ve learned in the chapter. The primary purpose of this book is to compile all of the topics needed for a beginner in one book, and provide all the resources needed, to make the process of studying for contests easier. Chapter 2 Elementary Techniques 2.1 Input and Output In your CS classes, you’ve probably implemented input and output using standard input and standard output, or using Scanner to read input and System.out.print to print output. In CodeForces and CSES, input and output are standard, and the above methods work. However, Scanner and System.out.print are slow when we have to handle inputting and outputting tens of thousands of lines. Thus, we use BufferedReader and PrintWriter instead, which are faster because they buffer the input and output and handle it all at once as opposed to parsing each line individually. However, in USACO, input is read from a file called problemname.in, and printing output to a file called problemname.out. Note that you’ll have to rename the .in and .out files. Essentially, replace every instance of the word template in the word below with the input/output file name, which should be given in the problem. In order to test a program, create a file called problemname.in, and then run the program. The output will be printed to problemname.out. Below, we have included Java example code for input and output in USACO. We import the entire util and io libraries for ease of use. The template is intentionally kept short so you can type it out, since use of prewritten code is not allowed in USACO as of the 2020-2021 season. import java.io.*; import java.util.*; public class template { public static void main(String[] args) throws IOException { BufferedReader r = new BufferedReader(new FileReader("template.in")); (cid:44)→ PrintWriter pw = new PrintWriter(new BufferedWriter(new (cid:44)→ FileWriter("template.out"))); StringTokenizer st = new StringTokenizer(r.readLine()); int n = Integer.parseInt(st.nextToken()); 5 CHAPTER 2. ELEMENTARY TECHNIQUES 6 r.close(); pw.close(); } } We have several important functions that are used in reading input and printing output: Method Description r.readLine() st.nextToken() Integer.parseInt Reads the next line of the input Reads the next token (up to a whitespace) and returns as a ‘String‘. Converts the ‘String‘ returned by the ‘StringTokenizer‘ to an ‘int‘. Double.parseDouble Converts the ‘String‘ returned by the ‘StringTokenizer‘ to a ‘double‘. Long.parseLong pw.println() pw.print() Converts the ‘String‘ returned by the ‘StringTokenizer‘ to a ‘long‘ Prints the argument to designated output stream and adds newline Prints the argument to designated output stream For example, if we’re reading the following input, 1 2 3 our code (inside the main method) will look like this: BufferedReader r = new BufferedReader(new FileReader("template.in")); PrintWriter pw = new PrintWriter(new BufferedWriter(new (cid:44)→ FileWriter("template.out"))); StringTokenizer st = new StringTokenizer(r.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); int c = Integer.parseInt(st.nextToken()); r.close(); pw.close(); Now, let’s suppose we wanted to read this input, which is presented on different lines, with different data types: 100000000000 SFDFSDFSDFD 3 Then our code would be CHAPTER 2. ELEMENTARY TECHNIQUES 7 BufferedReader r = new BufferedReader(new FileReader("template.in")); PrintWriter pw = new PrintWriter(new BufferedWriter(new (cid:44)→ FileWriter("template.out"))); StringTokenizer st = new StringTokenizer(r.readLine()); long a = Long.parseLong(st.nextToken()); st = new StringTokenizer(r.readLine()); String b = st.nextToken(); st = new StringTokenizer(r.readLine()); int c = Integer.parseInt(st.nextToken()); r.close(); pw.close(); Note how we have to re-declare the ‘StringTokenizer‘ every time we read in a new line. For CodeForces, CSES, and other contests that use standard input and output, here is a nicer template, which essentially functions as a faster Scanner: import java.io.*; import java.util.*; public class template { static class InputReader { BufferedReader reader; StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } String next() { // reads in the next string while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { // reads in the next int return Integer.parseInt(next()); CHAPTER 2. ELEMENTARY TECHNIQUES 8 } public long nextLong() { // reads in the next long return Long.parseLong(next()); } public double nextDouble() { // reads in the next double return Double.parseDouble(next()); } } static InputReader r = new InputReader(System.in); static PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args) { // YOUR CODE HERE pw.close(); // flushes the output once printing is done } } Here’s a brief description of the methods in our InputReader class, with an instance r, and PrintWriter with an instance pw. Method r.next() r.nextInt() r.nextLong() Description Reads the next token (up to a whitespace) and returns a String Reads the next token (up to a whitespace) and returns as an int Reads the next token (up to a whitespace) and returns as a long r.nextDouble() Reads the next token (up to a whitespace) and returns as a double Prints the argument to designated output stream and adds newline Prints the argument to designated output stream pw.println() pw.print() Here’s an example to show how input/output works. Let’s say we want to write a program that takes three numbers as input and prints their sum. // InputReader template code above static InputReader r = new InputReader(System.in); static PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args) { int a = r.nextInt(); int b = r.nextInt(); int c = r.nextInt() pw.println(a + b + c); CHAPTER 2. ELEMENTARY TECHNIQUES 9 pw.close(); } 2.2 Data Types There are several main data types that are used in contests: 32-bit and 64-bit integers, floating point numbers, booleans, characters, and strings. The 32-bit integer supports values between −2 147 483 648 and 2 147 483 647, which is roughly equal to ± 2×109. If the input, output, or any intermediate values used in calculations exceed the range of a 32-bit integer, then a 64-bit integer must be used. The range of the 64-bit integer is between −9 223 372 036 854 775 808 and 9 223 372 036 854 775 807 which is roughly equal to ± 9 × 1018. Contest problems are usually set such that the 64-bit integer is sufficient. If it’s not, the problem will ask for the answer modulo m, instead of the answer itself, where m is a prime. In this case, make sure to use 64-bit integers, and take the remainder of x modulo m after every step using x %= m;. Floating point numbers are used to store decimal values. It is important to know that floating point numbers are not exact, because the binary architecture of computers can only store decimals to a certain precision. Hence, we should always expect that floating point numbers are slightly off. Contest problems will accommodate this by either asking for the greatest integer less than 10k times the value, or will mark as correct any output that is within a certain (cid:15) of the judge’s answer. Boolean variables have two possible states: true and false. We’ll usually use booleans to mark whether a certain process is done, and arrays of booleans to mark which components of an algorithm have finished. Character variables represent a single Unicode character. They are returned when you access the character at a certain index within a string. Characters are represented using the ASCII standard, which assigns each character to a corresponding integer; this allows us to do arithmetic with them, for example, System.out.println('f' - 'a'); will print 5. Strings are effectively arrays of characters. You can easily access the character at a certain index and take substrings of the string. String problems on USACO are generally very easy and don’t involve any special data structures. Chapter 3 Time/Space Complexity and Algorithm Analysis In programming contests, there is a strict limit on program runtime. This means that in order to pass, your program needs to finish running within a certain timeframe. For USACO, this limit is 4 seconds for Java submissions. A conservative estimate for the number of operations the grading server can handle per second is 108. 3.1 Big O Notation and Complexity Calculations We want a method of characterizing how many operations it takes to run each algorithm, in terms of the input size n. Fortunately, this can be done relatively easily using Big O notation, which expresses worst-case complexity as a function of n, as n gets arbitrarily large. Complexity is an upper bound for the number of steps an algorithm requires, as a function of the input size. In Big O notation, we denote the complexity of a function as O(f (n)), where f (n) is a function without constant factors or lower-order terms. We’ll see some examples of how this works, as follows. The following code is O(1), because it executes a constant number of operations. int a = 5; int b = 7; int c = 4; int d = a + b + c + 153; Input and output operations are also assumed to be O(1). In the following examples, we assume that the code inside the loops is O(1). The time complexity of loops is the number of iterations that the loop runs multiplied by the amount of operations per iteration. The following code examples are both O(n). for(int i = 1; i <= n; i++){ // constant time code here } 10 CHAPTER 3. TIME/SPACE COMPLEXITY AND ALGORITHM ANALYSIS 11 int i = 0; while(i < n){ // constant time node here i++; } Because we ignore constant factors and lower order terms, for loops where we loop up to 5n + 17 or n + 457737 would also be O(n): We can find the time complexity of multiple loops by multiplying together the time complexities of each loop. The following example is O(nm), because the outer loop runs O(n) iterations and the inner loop O(m). for(int i = 1; i <= n; i++){ for(int j = 1; j <= m; j++){ // constant time code here } } If an algorithm contains multiple blocks, then its time complexity is the worst time complexity out of any block. For example, if an algorithm has an O(n) block and an O(n2) block, the overall time complexity is O(n2). Functions of different variables generally are not considered lower-order terms with respect to each other, so we must include both terms. For example, if an algorithm has an O(n2) block and an O(nm) block, the overall time complexity would be O(n2 + nm). 3.2 Common Complexities and Constraints Complexity factors that come from some common algorithms and data structures are as follows: • Mathematical formulas that just calculate an answer: O(1) • Unordered set/map: O(1) per operation • Binary search: O(log n) • Ordered set/map or priority queue: O(log n) per operation • Prime factorization of an integer, or checking primality or compositeness of an integer: √ O( n) • Reading in n items of input: O(n) • Iterating through an array or a list of n elements: O(n) CHAPTER 3. TIME/SPACE COMPLEXITY AND ALGORITHM ANALYSIS 12 • Sorting: usually O(n log n) for default sorting algorithms (mergesort, for example Collections.sort or Arrays.sort on objects) • Java Quicksort (Arrays.sort function on primitives on pathological worst-case data sets, don’t use this in CodeForces rounds. . . ): O(n2). • Iterating through all subsets of size k of the input elements: O(nk). For example, iterating through all triplets is O(n3). • Iterating through all subsets: O(2n) • Iterating through all permutations: O(n!) Here are conservative upper bounds on the value of n for each time complexity. You can probably get away with more than this, but this should allow you to quickly check whether an algorithm is viable. n Possible complexities n ≤ 10 n ≤ 20 n ≤ 80 n ≤ 400 n ≤ 7500 n ≤ 7 · 104 n ≤ 5 · 105 n ≤ 5 · 106 n ≤ 1012 n ≤ 1018 O(log2 n), O(log n), O(1) O(n!), O(n7), O(n6) O(2n · n), O(n5) O(n4) O(n3) O(n2) √ n) O(n O(n log n) O(n) n log n), O( O( n) √ √ Chapter 4 Built-in Data Structures A data structure determines how data is stored. (is it sorted? indexed? what operations does it support?) Each data structure supports some operations efficiently, while other operations are either inefficient or not supported at all. This chapter introduces the data structures in the Java standard library that are frequently used in competitive programming. Java default Collections data structures are designed to store any type of object. However, we usually don’t want this; instead, we want our data structures to only store one type of data, like integers, or strings. We do this by putting the desired data type within the <> brackets when declaring the data structure, as follows: ArrayList<String> list = new ArrayList<String>(); This creates an ArrayList structure that only stores objects of type String. For our examples below, we will primarily use the Integer data type, but note that you can have Collections of any object type, including Strings, other Collections, or user-defined objects. Collections data types always contain an add method for adding an element to the collection, and a remove method which removes and returns a certain element from the collection. They also support the size() method, which returns the number of elements in the data structure, and the isEmpty() method, which returns true if the data structure is empty, and false otherwise. 4.1 Dynamic Arrays You’re probably already familiar with regular (static) arrays. Now, there are also dynamic arrays (ArrayList in Java) that support all the functions that a normal array does, and can resize itself to accommodate more elements. In a dynamic array, we can also add and delete elements at the end in O(1) time. However, we need to be careful that we only add elements to the end of the ArrayList; insertion and deletion in the middle of the ArrayList is O(n). 13 CHAPTER 4. BUILT-IN DATA STRUCTURES 14 ArrayList<Integer> list = new ArrayList<Integer>(); // declare the dynamic array list.add(2); // [2] list.add(3); // [2, 3] list.add(7); // [2, 3, 7] list.add(5); // [2, 3, 7, 5] list.set(1, 4); // sets element at index 1 to 4 -> [2, 4, 7, 5] list.remove(1); // removes element at index 1 -> [2, 7, 5] // this remove method is O(n); to be avoided list.add(8); // [2, 7, 5, 8] list.remove(list.size()-1); // [2, 7, 5] // here, we remove the element from the end of the list; this is O(1). System.out.println(list.get(2)); // 5 To iterate through a static or dynamic array, we can use either the regular for loop or the for-each loop. Arrays.sort(arr) is used to sort a static array, and Collections.sort(list) a dynamic array. The default sort function sorts the array in ascending order. In array-based contest problems, we’ll use one-, two-, and three-dimensional static arrays most of the time. However, we can also have static arrays of dynamic arrays, dynamic arrays of static arrays, and so on. Usually, the choice between a static array and a dynamic array is just personal preference. 4.2 Stacks and the Various Types of Queues Stacks A stack is a Last In First Out (LIFO) data structure that supports three operations: push, which adds an element to the top of the stack, pop, which removes an element from the top of the stack, and peek, which retrieves the element at the top without removing it, all in O(1) time. Think of it like a real-world stack of papers. Stack<Integer> s = new Stack<Integer>(); s.push(1); // [1] s.push(13); // [1, 13] System.out.println(s.size()); // 2 s.pop(); // [1] System.out.println(s.peek()); // 1 s.pop(); // [] System.out.println(s.size()); // 0 Queues A queue is a First In First Out (FIFO) data structure that supports three operations of add, insertion at the back of the queue, poll, deletion from the front of the queue, and peek, CHAPTER 4. BUILT-IN DATA STRUCTURES 15 which retrieves the element at the front without removing it, all in O(1) time. Java doesn’t actually have a Queue class; it’s only an interface. The most commonly used implementation is the LinkedList, declared as follows: Queue q = new LinkedList();. Queue<Integer> q = new LinkedList<Integer>(); q.add(1); // [1] q.add(3); // [3, 1] q.poll(); // [3] q.add(4); // [4, 3] System.out.println(q.size()); // 2 System.out.println(q.peek()); // 4 Deques A deque (usually pronounced “deck”) stands for double ended queue and is a combination of a stack and a queue, in that it supports O(1) insertions and deletions from both the front and the back of the deque. In Java, the deque class is called ArrayDeque. The four methods for adding and removing are addFirst, removeFirst, addLast, and removeLast. The methods for retrieving the first and last elements without removing are peekFirst and peekLast. ArrayDeque<Integer> deque = new ArrayDeque<Integer>(); deque.addFirst(1); // [1] deque.addLast(2); // [1, 2] deque.addFirst(3); // [3, 1, 2] deque.addFirst(4); // [3, 1, 2, 4] deque.removeLast(); // [3, 1, 2] deque.removeFirst(); // [1, 2] Priority Queues A priority queue supports the following operations: insertion of elements, deletion of the element considered highest priority, and retrieval of the highest priority element, all in O(log n) time according to the number of elements in the priority queue. Priority is based on a comparator function, but by default the lowest element is at the front of the priority queue. The priority queue is one of the most important data structures in competitive programming, so make sure you understand how and when to use it. By default, the Priority Queue puts the lowest element at the front of the queue. PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); pq.add(4); // [4] pq.add(2); // [4, 2] pq.add(1); // [4, 2, 1] CHAPTER 4. BUILT-IN DATA STRUCTURES 16 pq.add(3); // [4, 3, 2, 1] System.out.println(pq.peek()); // 1 pq.poll(); // [4, 3, 2] pq.poll(); // [4, 3] pq.add(5); // [5, 4, 3] 4.3 Sets and Maps A set is a collection of objects that contains no duplicates. There are two types of sets: unordered sets (HashSet in Java), and ordered set (TreeSet in Java). Unordered Sets The unordered set works by hashing, which is assigning a usually-unique code to every variable/object which allows insertions, deletions, and searches in O(1) time, albeit with a high constant factor, as hashing requires a large constant number of operations. However, as the name implies, elements are not ordered in any meaningful way, so traversals of an unordered set will return elements in some arbitrary order. The operations on an unordered set are add, which adds an element to the set if not already present, remove, which deletes an element if it exists, and contains, which checks whether the set contains that element. HashSet<Integer> set = new HashSet<Integer>(); set.add(1); // [1] set.add(4); // [1, 4] in arbitrary order set.add(2); // [1, 4, 2] in arbitrary order set.add(1); // [1, 4, 2] in arbitrary order // the add method did nothing because 1 was already in the set System.out.println(set.contains(1)); // true set.remove(1); // [2, 4] in arbitrary order System.out.println(set.contains(5)); // false set.remove(0); // [2, 4] in arbitrary order // if the element to be removed does not exist, nothing happens for(int element : set){ System.out.println(element); } // You can iterate through an unordered set, but it will do so in arbitrary (cid:44)→ order Ordered Sets The second type of set data structure is the ordered or sorted set. Insertions, deletions, and searches on the ordered set require O(log n) time, based on the number of elements CHAPTER 4. BUILT-IN DATA STRUCTURES 17 in the set. As well as those supported by the unordered set, the ordered set also allows four additional operations: first, which returns the lowest element in the set, last, which returns the highest element in the set, lower, which returns the greatest element strictly less than some element, and higher, which returns the least element strictly greater than it. TreeSet<Integer> set = new TreeSet<Integer>(); set.add(1); // [1] set.add(14); // [1, 14] set.add(9); // [1, 9, 14] set.add(2); // [1, 2, 9, 14] System.out.println(set.higher(7)); // 9 System.out.println(set.higher(9)); // 14 System.out.println(set.lower(5)); // 2 System.out.println(set.first()); // 1 System.out.println(set.last()); // 14 set.remove(set.higher(6)); // [1, 2, 14] System.out.println(set.higher(23); // ERROR, no such element exists The primary limitation of the ordered set is that we can’t efficiently access the kth largest element in the set, or find the number of elements in the set greater than some arbitrary x. These operations can be handled using a data structure called an order statistic tree, but that is beyond the scope of this book. Maps A map is a set of ordered pairs, each containing a key and a value. In a map, all keys are required to be unique, but values can be repeated. Maps have three primary methods: one to add a specified key-value pairing, one to retrieve the value for a given key, and one to remove a key-value pairing from the map. Like sets, maps can be unordered (HashSet in Java) or ordered (TreeSet in Java). In an unordered map, hashing is used to support O(1) operations. In an ordered map, the entries are sorted in order of key. Operations are O(log n), but accessing or removing the next key higher or lower than some input k is also supported. Unordered Maps In the unordered map, the put(key, value) method assigns a value to a key and places the key and value pair into the map. The get(key) method returns the value associated with the key. The containsKey(key) method checks whether a key exists in the map. Lastly, remove(key) removes the map entry associated with the specified key. All of these operations are O(1), but again, due to the hashing, this has a high constant factor. HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); map.put(1, 5); // [(1, 5)] map.put(3, 14); // [(1, 5); (3, 14)] CHAPTER 4. BUILT-IN DATA STRUCTURES 18 map.put(2, 7); // [(1, 5); (3, 14); (2, 7)] map.remove(2); // [(1, 5); (3, 14)] System.out.println(map.get(1)); // 5 System.out.println(map.containsKey(7)); // false System.out.println(map.containsKey(1)); // true Ordered Maps The ordered map supports all of the operations that an unordered map supports, and additionally supports firstKey/firstEntry and lastKey/lastEntry, returning the lowest key/entry and the highest key/entry, as well as higherKey/higherEntry and lowerKey/ lowerEntry, returning the lowest key/entry strictly higher than the specified key, or the highest key/entry strictly lower than the specified key. TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>(); map.put(3, 5); // [(3, 5)] map.put(11, 4); // [(3, 5); (11, 4)] map.put(10, 491); // [(3, 5); (10, 491); (11, 4)] System.out.println(map.firstKey()); // 3 System.out.println(map.firstEntry()); // (3, 5) System.out.println(map.lastEntry()); // (11, 4) System.out.println(map.higherEntry(4)); // (10, 491) map.remove(11); // [(3, 5); (10, 491)] System.out.println(map.lowerKey(4)); // 3 System.out.println(map.lowerKey(3)); // ERROR A note on unordered sets and maps: In USACO contests, they’re generally fine, but in CodeForces contests, you should always use sorted sets and maps. This is because the built-in hashing algorithm is vulnerable to pathological data sets causing abnormally slow runtimes, in turn causing failures on some test cases. Multisets Lastly, there is the multiset, which is essentially a sorted set that allows multiple copies of the same element. While there is no Multiset in Java, we can implement one using the TreeMap from values to their respective frequencies. We declare the TreeMap implementation globally so that we can write functions for adding and removing elements from it. static TreeMap<Integer, Integer> multiset = new TreeMap<Integer, Integer>(); public static void main(String[] args){ ... } CHAPTER 4. BUILT-IN DATA STRUCTURES 19 static void add(int x){ if(multiset.containsKey(x)){ multiset.put(x, multiset.get(x) + 1); } else { multiset.put(x, 1); } } static void remove(int x){ multiset.put(x, multiset.get(x) - 1); if(multiset.get(x) == 0){ multiset.remove(x); } } The first, last, higher, and lower operations still function as intended; just use firstKey, lastKey, higherKey, and lowerKey respectively. 4.4 Problems Again, note that CSES’s grader is very slow, so don’t worry if you encounter a Time Limit Exceeded verdict; as long as you pass the majority of test cases within the time limit, you can consider the problem solved, and move on. 1. CSES Problem Set Task 1621: Distinct Numbers https://cses.fi/problemset/task/1621 2. CSES Problem Set Task 1084: Apartments https://cses.fi/problemset/task/1084 3. CSES Problem Set Task 1091: Concert Tickets https://cses.fi/problemset/task/1091 4. CSES Problem Set Task 1163: Traffic Lights https://cses.fi/problemset/task/1163 5. CSES Problem Set Task 1164: Room Allocation https://cses.fi/problemset/task/1164 Part II Bronze 20 Chapter 5 Simulation In many problems, we can simply simulate what we’re told to do by the problem statement. Since there’s no formal algorithm involved, the intent of the problem is to assess competence with one’s programming language of choice and knowledge of built-in data structures. At least in USACO Bronze, when a problem statement says to find the end result of some process, or to find when something occurs, it’s usually sufficient to simulate the process. 5.1 Example 1 Alice and Bob are standing on a 2D plane. Alice starts at the point (0, 0), and Bob starts at the point (R, S) (1 ≤ R, S ≤ 1000). Every second, Alice moves M units to the right, and N units up. Every second, Bob moves P units to the left, and Q units down. (1 ≤ M, N, P, Q ≤ 10). Determine if Alice and Bob will ever meet (be at the same point at the same time), and if so, when. INPUT FORMAT: The first line of the input contains R and S. The second line of the input contains M , N , P , and Q. OUTPUT FORMAT: Please output a single integer containing the number of seconds after the start at which Alice and Bob meet. If they never meet, please output −1. Solution We can simulate the process. After inputting the values of R, S, M , N , P , and Q, we can keep track of Alice’s and Bob’s x- and y-coordinates. To start, we initialize variables for their respective positions. Alice’s coordinates are initially (0, 0), and Bob’s coordinates are (R, S) respectively. Every second, we increase Alice’s x-coordinate by M and her y-coordinate by N , and decrease Bob’s x-coordinate by P and his y-coordinate by Q. Now, when do we stop? First, if Alice and Bob ever have the same coordinates, then we are done. Also, since Alice strictly moves up and to the right and Bob strictly moves down and to the left, if Alice’s x- or y-coordinates are ever greater than Bob’s, then it is impossible for them to meet. Example code will be displayed below (Here, as in other examples, input processing will be omitted): 21 CHAPTER 5. SIMULATION 22 int ax = 0; int ay = 0; // alice's x and y coordinates int bx = r; int by = s; // bob's x and y coordinates int t = 0; // keep track of the current time while(ax < bx && ay < by){ // every second, update alice's and bob's coordinates and the time ax += m; ay += n; bx -= p; by -= q; t++; } if(ax == bx && ay == by){ // if they are in the same location out.println(t); // they meet at time t } else { out.println(-1); // they never meet } out.close(); // flush the output 5.2 Example 2 There are N buckets (5 ≤ N ≤ 105), each with a certain capacity Ci (1 ≤ Ci ≤ 100). One day, after a rainstorm, each bucket is filled with Ai units of water (1 ≤ Ai ≤ Ci). Charlie then performs the following process: he pours bucket 1 into bucket 2, then bucket 2 into bucket 3, and so on, up until pouring bucket N − 1 into bucket N . When Charlie pours bucket B into bucket B + 1, he pours as much as possible until bucket B is empty or bucket B + 1 is full. Find out how much water is in each bucket once Charlie is done pouring. INPUT FORMAT: The first line of the input contains N . The second line of the input contains the capacities of the buckets, C1, C2, . . . , Cn. The third line of the input contains the amount of water in each bucket A1, A2, . . . , An. OUTPUT FORMAT: Please print one line of output, containing N space-separated integers: the final amount of water in each bucket once Charlie is done pouring. Solution: Once again, we can simulate the process of pouring one bucket into the next. The amount of water poured from bucket B to bucket B + 1 is the smaller of the amount of water in bucket B (after all previous operations have been completed) and the remaining space in bucket B + 1, which is CB+1 − AB+1. We can just handle all of these operations in order, using an array C to store the maximum capacities of each bucket, and an array A to store the current water level in each bucket, which we update during the process. Example code is below (note that arrays are zero-indexed, so the indices of our buckets go from 0 to N − 1 rather than from 1 to N ). CHAPTER 5. SIMULATION 23 for(int i = 0; i < n-1; i++){ int amt = Math.min(A[i], C[i+1]-A[i+1]); // the amount of water to be poured is the lesser of // the amount of water in the current bucket and // the amount of additional water that the next bucket can hold A[i] -= amt; // remove the amount from the current bucket A[i+1] += amt; // add it to the next bucket } for(int i = 0; i < n; i++){ pw.print(A[i] + " "); // print the amount of water in each bucket at the end } pw.println(); // print newline pw.close(); // flush the output 5.3 Problems 1. USACO December 2018 Bronze Problem 1: Mixing Milk http://www.usaco.org/index.php?page=viewproblem2&cpid=855 2. USACO December 2017 Bronze Problem 3: Milk Measurement http://www.usaco.org/index.php?page=viewproblem2&cpid=761 3. USACO US Open 2017 Bronze Problem 1: The Lost Cow http://www.usaco.org/index.php?page=viewproblem2&cpid=735 4. USACO February 2017 Bronze Problem 3: Why Did the Cow Cross the Road III http://www.usaco.org/index.php?page=viewproblem2&cpid=713 5. USACO January 2016 Bronze Problem 3: Mowing the Field http://www.usaco.org/index.php?page=viewproblem2&cpid=593 6. USACO December 2017 Bronze Problem 2: The Bovine Shuffle http://usaco.org/index.php?page=viewproblem2&cpid=760 7. USACO February 2016 Bronze Problem 2: Circular Barn http://usaco.org/index.php?page=viewproblem2&cpid=616 Chapter 6 Complete Search In many problems (especially in Bronze), it’s sufficient to check all possible cases in the solution space, whether it be all elements, all pairs of elements, or all subsets, or all permutations. Unsurprisingly, this is called complete search (or brute force), because it completely searches the entire solution space. 6.1 Example 1 You are given N (3 ≤ N ≤ 5000) integer points on the coordinate plane. Find the square of the maximum Euclidean distance (aka length of the straight line) between any two of the points. INPUT FORMAT: The first line contains an integer N . The second line contains N integers, the x-coordinates of the points: x1, x2, . . . , xn (−1000 ≤ xi ≤ 1000). The third line contains N integers, the y-coordinates of the points: y1, y2, . . . , yn (−1000 ≤ yi ≤ 1000). OUTPUT FORMAT: Print one integer, the square of the maximum Euclidean distance between any two of the points. Solution: We can brute-force every pair of points and find the square of the distance between them, by squaring the formula for Euclidean distance: distance2 = (x2 − x1)2 + (y2 − y1)2. Thus, we store the coordinates in arrays X[] and Y[], such that X[i] and Y[i] are the x- and y-coordinates of the ith point, respectively. Then, we iterate through all possible pairs of points, using a variable max to store the maximum square of distance between any pair seen so far, and if the square of the distance between a pair is greater than our current maximum, 24 CHAPTER 6. COMPLETE SEARCH 25 we set our current maximum to it. Algorithm: Finds the maximum Euclidean distance between any two of the given points Function maxDist : points an array of n ordered pairs Input Output : the maximum Euclidean distance between any two of the points max ← 0 for i ← 1 to n do for j ← i + 1 to n do if dist(points[i], points[j])2 > max then max ← dist(points[i], points[j])2 end end end return max int max = 0; // storing the current maximum for(int i = 0; i < n; i++){ // for each first point for(int j = i+1; j < n; j++){ // for each second point int dx = x[i] - x[j]; int dy = y[i] - y[j]; max = Math.max(max, dx*dx + dy*dy); // if the square of the distance between the two points is greater than // our current maximum, then update the maximum } } pw.println(max); A couple notes: first, since we’re iterating through all pairs of points, we start the j loop from j = i + 1 so that point i and point j are never the same point. Furthermore, it makes it so that each pair is only counted once. In this problem, it doesn’t matter whether we double-count pairs or whether we allow i and j to be the same point, but in other problems where we’re counting something rather than looking at the maximum, it’s important to be careful that we don’t overcount. Secondly, the problem asks for the square of the maximum Euclidean distance between any two points. Some students may be tempted to maintain the maximum distance in a variable, and then square it at the end when outputting. However, the problem here is that while the square of the distance between two integer points is always an integer, the distance itself isn’t guaranteed to be an integer. Thus, we’ll end up shoving a non-integer value into an integer variable, which truncates the decimal part. Using a floating point variable isn’t likely to work either, due to precision errors (use of floating point decimals should generally be avoided when possible). CHAPTER 6. COMPLETE SEARCH 26 6.2 Generating Permutations A permutation is a reordering of a list of elements. Some problems will ask for an ordering of elements that satisfies certain conditions. In these problems, if N ≤ 10, we can probably iterate through all permutations and check each permutation for validity. For a list of N elements, there are N ! ways to permute them, and generally we’ll need to read through each permutation once to check its validity, for a time complexity of O(N · N !). In Java, we’ll have to implement this ourselves, which is called Heap’s Algorithm (no relation to the heap data structure). What’s going to be in the check function depends on the problem, but it should verify whether the current permutation satisfies the constraints given in the problem. As an example, here are the permutations generated by Heap’s Algorithm for [1, 2, 3]: [1, 2, 3], [2, 1, 3], [3, 1, 2], [1, 3, 2], [2, 3, 1], [3, 2, 1] Algorithm: Iterate over all permutations of a given input array, performing some action on each permutation Function generatePermutations Input : An array arr, and its length k if k = 1 then process the current permutation else generatePermutations (arr, k − 1) for i ← 0 to k − 1 do if k is even then swap indices i and k − 1 of arr else swap indices 0 and k − 1 of arr end generatePermutations (arr, k − 1) end end Code for iterating over all permutations is as follows: // this method is called with k equal to the length of arr static void generate(int[] arr, int k){ if(k == 1){ check(arr); // check the current permutation for validity } else { generate(arr, k-1); for(int i = 0; i < k-1; i++){ if(k % 2 == 0){ swap(arr, i, k-1); // swap indices i and k-1 of arr CHAPTER 6. COMPLETE SEARCH 27 } else { swap(arr, 0, k-1); // swap indices 0 and k-1 of arr } generate(arr, k-1); } } } 6.3 Problems 1. USACO February 2020 Bronze Problem 1: Triangles http://usaco.org/index.php?page=viewproblem2&cpid=1011 2. USACO January 2020 Bronze Problem 2: Photoshoot http://www.usaco.org/index.php?page=viewproblem2&cpid=988 (Hint: Figure out what exactly you’re complete searching) 3. USACO December 2019 Bronze Problem 1: Cow Gymnastics http://usaco.org/index.php?page=viewproblem2&cpid=963 (Hint: Brute force over all possible pairs) 4. USACO February 2016 Bronze Problem 1: Milk Pails http://usaco.org/index.php?page=viewproblem2&cpid=615 5. USACO January 2018 Bronze Problem 2: Lifeguards http://usaco.org/index.php?page=viewproblem2&cpid=784 (Hint: Try removing each lifeguard one at a time). 6. USACO December 2019 Bronze Problem 2: Where Am I? http://usaco.org/index.php?page=viewproblem2&cpid=964 (Hint: Brute force over all possible substrings) 7. (Permutations) USACO December 2019 Bronze Problem 3: Livestock Lineup http://usaco.org/index.php?page=viewproblem2&cpid=965 8. (Permutations) CSES Problem Set Task 1624: Chessboard and Queens https://cses.fi/problemset/task/1624 9. USACO US Open 2016 Bronze Problem 3: Field Reduction http://www.usaco.org/index.php?page=viewproblem2&cpid=641 (Hint: For this problem, you can’t do a full complete search; you have to do a reduced search) 10. USACO December 2018 Bronze Problem 3: Back and Forth http://www.usaco.org/index.php?page=viewproblem2&cpid=857 (This problem is relatively hard) Chapter 7 Additional Bronze Topics 7.1 Square and Rectangle Geometry The extent of “geometry” problems on USACO Bronze are usually quite simple and limited to intersections and unions of squares and rectangles. These usually only include two or three squares or rectangles, in which case you can simply draw out cases on paper, which should logically lead to a solution. In Java, the Rectangle class may be of use for finding intersections and unions of rectangles. Here are some of the functions that the Rectangle class has: • Find whether a certain point or rectangle is contained within another rectangle • Find the intersection or union of two rectangles • Translate, scale, or shrink rectangles For exact details and documentation, refer to the Rectangle class page on the official javadoc: https://docs.oracle.com/javase/7/docs/api/java/awt/Rectangle.html The problems given at the end of the chapter should encompass all the techniques you need to know for geometry problems in the Bronze division. 7.2 Ad-hoc Ad-hoc problems are problems that don’t fall into any standard algorithmic category with well known solutions. They are usually unique problems intended to be solved with unconventional techniques. In ad-hoc problems, it’s helpful to look at the constraints given in the problem and devise potential time complexities of solutions; this, combined with details in the problem statement itself, may give an outline of the solution. Unfortunately, since ad-hoc problems don’t have solutions consisting of well known algorithms, we can’t systematically teach you how to do them. The best way of learning how to do ad-hoc is to practice. Of course, the problem solving intuition from math contests (if you did them) is quite helpful, but otherwise, you can develop this intuition from practicing ad-hoc problems. 28 CHAPTER 7. ADDITIONAL BRONZE TOPICS 29 While solving these problems, make sure to utilize what you’ve learned about the built-in data structures and algorithmic complexity analysis, from chapters 2, 3, and 4. Since ad-hoc problems comprise a significant portion of bronze problems, we’ve included a large selection of them below for your practice. 7.3 Problems Square and Rectangle Geometry 1. USACO December 2017 Bronze Problem 1: Blocked Billboard http://usaco.org/index.php?page=viewproblem2&cpid=759 2. USACO December 2018 Bronze Problem 1: Blocked Billboard II http://usaco.org/index.php?page=viewproblem2&cpid=783 3. CodeForces Round 587 (Div. 3) Problem C: White Sheet https://codeforces.com/contest/1216/problem/C 4. USACO December 2016 Bronze Problem 1: Square Pasture http://usaco.org/index.php?page=viewproblem2&cpid=663 Ad-hoc problems 5. USACO January 2016 Bronze Problem 1: Promotion Counting http://usaco.org/index.php?page=viewproblem2&cpid=591 6. USACO January 2020 Bronze Problem 1: Word Processor http://usaco.org/index.php?page=viewproblem2&cpid=987 7. USACO US Open 2019 Bronze Problem 1: Bucket Brigade http://usaco.org/index.php?page=viewproblem2&cpid=939 8. USACO January 2018 Bronze Problem 3: Out of Place http://usaco.org/index.php?page=viewproblem2&cpid=785 9. USACO December 2016 Bronze Problem 2: Block Game http://usaco.org/index.php?page=viewproblem2&cpid=664 10. USACO February 2020 Bronze Problem 3: Swapity Swap http://usaco.org/index.php?page=viewproblem2&cpid=1013 (This problem is quite hard for bronze.) 11. USACO February 2018 Bronze Problem 1: Teleportation http://usaco.org/index.php?page=viewproblem2&cpid=807 12. USACO February 2018 Bronze Problem 2: Hoofball http://usaco.org/index.php?page=viewproblem2&cpid=808 CHAPTER 7. ADDITIONAL BRONZE TOPICS 30 13. USACO US Open 2019 Bronze Problem 3: Cow Evolution http://usaco.org/index.php?page=viewproblem2&cpid=941 (Warning: This problem is extremely difficult for bronze.) Part III Silver 31 Chapter 8 Sorting and comparators 8.1 Comparators Java has built-in functions for sorting: Arrays.sort(arr) for arrays, and Collections. sort(list) for ArrayLists. However, if we use custom objects, or if we want to sort elements in a different order, then we’ll need to use a Comparator. Normally, sorting functions rely on moving objects with a lower value ahead of objects with a higher value if sorting in ascending order, and vice versa if in descending order. This is done through comparing two objects at a time. What a Comparator does is compare two objects as follows, based on our comparison criteria: • If object x is less than object y, return a negative number • If object x is greater than object y, return a positive number • If object x is equal to object y, return 0. In addition to returning the correct number, comparators should also satisfy the following conditions: • The function must be consistent with respect to reversing the order of the arguments: if compare(x, y) is positive, then compare(y, x) should be negative and vice versa • The function must be transitive. If compare(x, y) > 0 and compare(y, z) > 0, then compare(x, z) > 0. Same applies if the compare functions return negative numbers. • Equality must be consistent. If compare(x, y) = 0, then compare(x, z) and compare(y, z) must both be positive, both negative, or both zero. Note that they don’t have to be equal, they just need to have the same sign. Java has default functions for comparing ints, longs, and doubles. The Integer.compare(), Long.compare(), and Double.compare() functions take two arguments x and y and compare them as described above. Now, there are two ways of implementing this in Java: Comparable, and Comparator. They essentially serve the same purpose, but Comparable is generally easier and shorter to 32 CHAPTER 8. SORTING AND COMPARATORS 33 code. Comparable is a function implemented within the class containing the custom object, while Comparator is its own class. For our example, we’ll use a Person class that contains a person’s height and weight, and sort in ascending order by height. If we use Comparable, we’ll need to put implements Comparable<Person> into the heading of the class. Furthermore, we’ll need to implement the compareTo method. Essentially, compareTo(x) is the compare function that we described above, with the object itself as the first argument: compare(self, x). static class Person implements Comparable<Person>{ int height, weight; public Person(int h, int w){ height = h; weight = w; } public int compareTo(Person p){ return Integer.compare(height, p.height); } } When using Comparable, we can just call Arrays.sort(arr) or Collections.sort(list) on the array or list as usual. If instead we choose to use Comparator, we’ll need to declare a second Comparator class, and then implement that: static class Person{ int height, weight; public Person(int h, int w){ height = h; weight = w; } } static class Comp implements Comparator<Person>{ public int compare(Person a, Person b){ return Integer.compare(a.height, b.height); } } When using Comparator, the syntax for using the built-in sorting function requires a second argument: Arrays.sort(arr, new Comp()), or Collections.sort(list, new Comp()). If we instead wanted to sort in descending order, this is also very simple. Instead of the comparing function returning Integer.compare(x, y) of the arguments, it should instead return -Integer.compare(x, y). CHAPTER 8. SORTING AND COMPARATORS 34 8.2 Sorting by Multiple Criteria Now, suppose we wanted to sort a list of Persons in ascending order, primarily by height and secondarily by weight. We can do this quite similarly to how we handled sorting by one criterion earlier. What the compareTo function needs to do is to compare the weights if the heights are equal, and otherwise compare heights, as that’s the primary sorting criterion. static class Person implements Comparable<Person>{ int height, weight; public Person(int h, int w){ height = h; weight = w; } public int compareTo(Person p){ if(height == p.height){ return Integer.compare(weight, p.weight); } else { return Integer.compare(height, p.height); } } } Sorting with more criteria is done similarly. An alternative way of representing custom objects is with arrays. Instead of using a custom object to store data about each person, we can simply use int[], where each int array is of size 2, and stores pairs of height, weight, probably in the form of a list like ArrayList<int[]>. Since arrays aren’t objects in the usual sense, we need to use Comparator. Example for sorting by the same two criteria as above: static class Comp implements Comparator<int[]>{ public int compare(int[] a, int[] b){ if(a[0] == b[0]){ return Integer.compare(a[1], b[1]); } else { return Integer.compare(a[0], b[0]); } } } I don’t recommend using arrays to represent objects, mostly because it’s confusing, but it’s worth noting that some competitors do this. 8.3 Problems 1. USACO US Open 2018 Silver Problem 2: Lemonade Line http://www.usaco.org/index.php?page=viewproblem2&cpid=835 CHAPTER 8. SORTING AND COMPARATORS 35 2. CodeForces Round 633 (Div. 2) Problem B: Sorted Adjacent Differences https://codeforces.com/problemset/problem/1339/B 3. CodeForces Round 579 (Div. 3) Problem E: Boxers https://codeforces.com/problemset/problem/1203/E 4. USACO January 2019 Silver Problem 3: Mountain View http://www.usaco.org/index.php?page=viewproblem2&cpid=896 5. USACO US Open 2016 Silver Problem 1: Field Reduction http://www.usaco.org/index.php?page=open16results Chapter 9 Greedy Algorithms Greedy algorithms are algorithms that select the most optimal choice at each step, instead of looking at the solution space as a whole. This reduces the problem to a smaller problem at each step. However, as greedy algorithms never recheck previous steps, they sometimes lead to incorrect answers. Moreover, in a certain problem, there may be more than one possible greedy algorithm; usually only one of them is correct. This means that we must be extremely careful when using the greedy method. However, when they are correct, greedy algorithms are extremely efficient. Greedy is not a single algorithm, but rather a way of thinking that is applied to problems. There’s no one way to do greedy algorithms. Hence, we use a selection of well-known examples to help you understand the greedy paradigm. Usually, when using a greedy algorithm, there is a heuristic or value function that determines which choice is considered most optimal. 9.1 Introductory Example: Studying Algorithms Steph wants to improve her knowledge of algorithms over winter break. She has a total of X (1 ≤ X ≤ 104) minutes to dedicate to learning algorithms. There are N (1 ≤ N ≤ 100) algorithms, and each one of them requires ai (1 ≤ ai ≤ 100) minutes to learn. Find the maximum number of algorithms she can learn. The solution is quite simple. The first observation we make is that Steph should prioritize learning algorithms from easiest to hardest; in other words, start with learning the algorithm that requires the least amount of time, and then choose further algorithms in increasing order of time required. Let’s look at the following example: X = 15, N = 6, ai = {4, 3, 8, 4, 7, 3} After sorting the array, we have {3, 3, 4, 4, 7, 8}. Within the maximum of 15 minutes, Steph can learn four algorithms in a total of 3 + 3 + 4 + 4 = 14 minutes. The implementation of this algorithm is very simple. We sort the array, and then take as many elements as possible while the sum of times of algorithms chosen so far is less than X. Sorting the array takes O(N log N ) time, and iterating through the array takes O(N ) time, for a total time complexity of O(N log N ). 36 CHAPTER 9. GREEDY ALGORITHMS 37 // read in the input, store the algorithms in int[] algorithms Arrays.sort(algorithms); int minutes = 0; // number of minutes used so far int i = 0; while(minutes + algorithms[i] <= x){ // while there is enough time, learn more algorithms minutes += algorithms[i]; i++; } pw.println(i); // print the ans pw.close(); 9.2 Example: The Scheduling Problem There are N events, each described by their starting and ending times. Jason would like to attend as many events as possible, but he can only attend one event at a time, and if he chooses to attend an event, he must attend the entire event. Traveling between events is instantaneous. Earliest Ending Next Event (Correct) The correct approach to this problem is to always select the next possible event that ends as soon as possible. A brief explanation of correctness is as follows. If we have two events E1 and E2, with E2 ending later than E1, then it is always optimal to select E1. This is because selecting E1 gives us more choices for future events. If we can select an event to go after E2, then that event can also go after E1, because E1 ends first. Thus, the set of events that can go after E2 is a subset of the events that can go after E1, making E1 the optimal choice. For the following code, let’s say we have the array events of events, which each contain a start and an end point. We’ll be using the following static class to store each event (a review of the previous chapter!) static class Event implements Comparable<Event>{ int start; int end; public Event(int s, int e){ start = s; end = e; } public int compareTo(Event e){ CHAPTER 9. GREEDY ALGORITHMS 38 return Integer.compare(this.end, e.end); } } // read in the input, store the events in Event[] events. Arrays.sort(events); // sorts by comparator we defined above int currentEventEnd = -1; // end of event currently attending int ans = 0; // how many events were attended? for(int i = 0; i < n; i++){ // process events in order of end time if(events[i].start >= currentEventEnd){ // if event can be attended // we know that this is the earliest ending event that we can attend // because of how the events are sorted currentEventEnd = events[i].end; ans++; } } pw.println(ans); pw.close(); Earliest Starting Next Event (Incorrect) To emphasize the importance of selecting the right criteria, we review an incorrect solution that always selects the next possible event that begins as soon as possible. Let’s look at the following example, where the selected events are highlighted in red: In this case, the greedy algorithm selects to attend only one event. However, the optimal solution would be the following: 9.3 Failure Cases of Greedy Algorithms We’ll provide a few common examples of when greedy fails, so that you can avoid falling into obvious traps and wasting time getting wrong answers in contest. CHAPTER 9. GREEDY ALGORITHMS 39 Coin Change This problem gives several coin denominations, and asks for the minimum number of coins needed to make a certain value. The greedy algorithm of taking the largest possible coin denomination that fits in the remaining capacity can be used to solve this problem only in very specific cases (it can be proven that it works for the American as well as the Euro coin systems). However, it doesn’t work in the general case. Knapsack The knapsack problem gives a number of items, each having a weight and a value, and we want to choose a subset of these items. We are limited to a certain weight, and we want to maximize the value of the items that we take. Let’s take the following example, where we have a maximum capacity of 4: Item Weight Value Value Per Weight A B C 3 2 2 18 10 10 6 5 5 If we use greedy based on highest value first, we choose item A and then we are done, as we don’t have remaining weight to fit either of the other two. Using greedy based on value per weight again selects item A and then quits. However, the optimal solution is to select items B and C, as they combined have a higher value than item A alone. In fact, there is no working greedy solution. The solution to this problem uses dynamic programming, which is beyond the scope of this book. 9.4 Problems 1. USACO December 2015 Silver Problem 2: High Card Wins http://usaco.org/index.php?page=viewproblem2&cpid=571 2. USACO February 2018 Silver Problem 1: Rest Stops http://www.usaco.org/index.php?page=viewproblem2&cpid=810 3. USACO February 2017 Silver Problem 1: Why Did The Cow Cross The Road http://www.usaco.org/index.php?page=viewproblem2&cpid=714 Chapter 10 Graph Theory Graph theory is one of the most important topics at the Silver level and above. Graphs can be used to represent many things, from images to wireless signals, but one of the simplest analogies is to a map. Consider a map with several cities and highways connecting the cities. Some of the problems relating to graphs are: • If we have a map with some cities and roads, what’s the shortest distance I have to travel to get from point A to point B? • Consider a map of cities and roads. Is city A connected to city B? Consider a region to be a group of cities such that each city in the group can reach any other city in said group, but no other cities. How many regions are in this map, and which cities are in which region? 10.1 Graph Basics Graphs are made up of nodes and edges, where nodes are connected by edges. Graphs can have either weighted edges, in which each edge has a certain length, or unweighted, in which case all edges have the same length. Edges are either directed, which means they can be traveled upon in one direction, or undirected, which means that they can be traveled upon in both directions. 4 2 6 5 1 3 5 5 2 1 4 4 2 −1 2 3 3 5 6 Figure 10.1: An undirected unweighted graph (left) and a directed weighted graph (right) 40 CHAPTER 10. GRAPH THEORY 41 A connected component is a set of nodes within which any node can reach any other node. For example, in this graph, nodes 1, 2, and 3 are a connected component, nodes 4 and 5 are a connected component, and node 6 is its own component. 3 1 2 6 4 5 Figure 10.2: Connected components in a graph 10.2 Trees A tree is a special type of graph satisfying two constraints: it is acyclic, meaning there are no cycles, and the number of edges is one less than the number of nodes. Trees satisfy the property that for any two nodes A and B, there is exactly one way to travel between A and B. 1 6 3 7 2 5 4 Figure 10.3: A tree graph The root of a tree is the one vertex that is placed at the top, and is where we usually start our tree traversals from. Usually, problems don’t tell us where the tree is rooted at, and it usually doesn’t matter either; trees can be arbitrarily rooted (here, we’ll use the convention of rooting at index 1). Every node except the root node has a parent. The parent of a node s is defined as follows: On the path from the root to s, the node that is one closer to the root than s is the parent of s. Each non-root node has a unique parent. Child nodes are the opposite. They lie one farther away from the root than their parent node. Unlike parent nodes, these are not unique. Each node can have arbitrarily many child nodes, and nodes can also have zero children. If a node s is the parent of a node t, then t is the child node of s. A leaf node is a node that has no children. Leaf nodes can be identified quite easily because there is only one edge adjacent to them. CHAPTER 10. GRAPH THEORY 42 In our example tree above, node 1 is the root, nodes 2 and 3 are children of node 1, nodes 4, 5, and 6 are children of 2, and node 7 is the child of 3. Nodes 4, 5, 6, and 7 are leaf nodes. 10.3 Graph Representations Usually, in a graph with N edges and M edges, we’ll number the nodes 0 through N − 1. If the problem gives the nodes numbered 1 through N , simply decrease the endpoint node numbers of edges by 1 as you input them, in order to accommodate zero-indexing of arrays. However, in problem statements, input and output, the node labels will usually be 1 through N , so that’s what we’ll use in our examples. Graphs will usually be given in an input format similar to the following: First, integers N and M denoting the number of nodes and edges, respectively. Then, M lines, each with integers a and b, representing edges; if the graph is undirected, then there is an edge between nodes a and b, and if the graph is directed, then there is an edge from a to b. For example, the input below would be for the following graph (without the comments): 6 7 // 6 nodes, 7 edges // the following lines represent edges. 1 2 1 4 1 5 2 3 2 4 3 5 4 6 4 2 6 5 1 3 Figure 10.4: The graph corresponding to the above input Graphs can be represented in three ways: Adjacency List, Adjacency Matrix, and Edge List. Regardless of how the graph is represented, it’s important that it be stored globally and statically, because we need to be able to access it from outside the main method, and call the graph searching and traversal methods on it. CHAPTER 10. GRAPH THEORY 43 Adjacency List The adjacency list is the most commonly used method of storing graphs. When we use DFS, BFS, Dijkstra’s, or other single-source graph traversal algorithms, we’ll want to use an adjacency list. In an adjacency list, we maintain a length N array of lists. Each list stores the neighbors of one node. In an undirected graph, if there is an edge between node a and node b, we add a to the list of b’s neighbors, and b to the list of a’s neighbors. In a directed graph, if there is an edge from node a to node b, we add b to the list of a’s neighbors, but not vice versa. 4 4 2 2 1 3 6 5 3 4 1 3 9 5 Figure 10.5: An example of a weighted undirected graph Adjacency list representation of the graph in fig. 10.5: adj[0] adj[1] adj[2] adj[3] adj[4] adj[5] (1, 9), (3, 4), (4, 3) (0, 9), (2, 5), (3, 2) (1, 5), (4, 4), (5, 1) (0, 4), (1, 2), (5, 3) (0, 3), (2, 4) (2, 1), (3, 3) Adjacency lists take up O(N + M ) space, because each node corresponds to one list of neighbors, and each edge corresponds to either one or two endpoints (directed vs undirected). In an adjacency list, we can find (and iterate through) the neighbors of a node easily. Hence, the adjacency list is the graph representation we should be using most of the time. Often, we’ll want to maintain a array visited, which is a boolean array representing whether each node has been visited. When we visit node k (0-indexed), we mark visited[k] true, so that we know not to return to it. Code for setting up an adjacency list is as follows: static int n, m; // number of nodes and edges static ArrayList<Integer>[] adj; // adjacency list public static void main(String[] args){ n = r.nextInt(); // reads in number of nodes m = r.nextInt(); // reads in number of edges CHAPTER 10. GRAPH THEORY 44 adj = new ArrayList[n]; // adjacency list // Java doesn't allow ArrayList<Integer>[n] boolean[] visited = new boolean[n]; for(int i = 0; i < n; i++){ adj[i] = new ArrayList<Integer>(); // initializes the ArrayLists } for(int i = 0; i < m; i++){ // reading in each of the m edges int a = r.nextInt()-1; // we subtract 1 because our array is zero-indexed (cid:44)→ int b = r.nextInt()-1; adj[a].add(b); adj[b].add(a); // omit this line if the graph is directed } } If we’re dealing with a weighted graph, we’ll declare an Edge class or struct that stores two variables: the second endpoint of the edge, and the weight of the edge, and we store an array of lists of edges rather than an array of lists of integers. static class Edge{ int to; int weight; public Edge(int to, int weight){ this.to = to; this.edge = edge; } } Adjacency Matrix Another way of representing graphs is the adjacency matrix, which is an N by N 2- dimensional array that stores for each pair of indices (a, b), stores whether there is an edge between a and b. Start by initializing every entry in the matrix to zero (this is done automatically in Java), and then for undirected graphs, for each edge between indices a and b, set adj[a][b] and adj[b][a] to 1 (if unweighted) or the edge weight (if weighted). If the graph is directed, for an edge from a to b, only set adj[a][b]. CHAPTER 10. GRAPH THEORY 45 4 4 2 2 1 3 6 5 3 4 1 3 9 5 Figure 1.5 repeated for convenience Adjacency matrix representation of the graph in fig. 1.5: × 0 1 2 3 4 5 0 0 9 0 4 3 0 1 9 0 5 2 0 0 2 0 5 0 0 4 1 3 4 2 0 0 0 3 4 3 0 4 0 0 0 5 0 0 1 3 0 0 At the Silver level, we generally won’t be using the adjacency matrix much, but it’s helpful to know if it does come up. The primary use of the adjacency matrix is the Floyd-Warshall algorithm, which is beyond the scope of this book. Code for setting up an adjacency matrix is as follows: static int n, m; // number of nodes and edges static int[][] adj; // adj matrix public static void main(String[] args){ n = r.nextInt(); m = r.nextInt(); adj = new int[n][n]; for(int i = 0; i < m; i++){ // read in each of the m edges int a = r.nextInt()-1; int b = r.nextInt()-1; adj[a][b] = 1; // or set equal to w if graph is weighted adj[b][a] = 1; // or set equal to w if graph is weighted; // ignore above line if graph is directed } } CHAPTER 10. GRAPH THEORY 46 Edge List The last graph representation is the edge list. Usually, we use this in weighted undirected graphs when we want to sort the edges by weight (for DSU, for example; see section 10.6). In the edge list, we simply store a single list of all the edges, in the form (a, b, w) where a and b are the nodes that the edge connects, and w is the edge weight. Note that in an edge list, we do NOT add each edge twice; there is only one place for us to add the edges, so we only do so once. 4 4 2 2 1 3 6 5 3 4 1 3 9 5 Figure 1.5 repeated for convenience Edge list representation of the graph in fig. 1.5: (0, 1, 9), (0, 3, 4), (0, 4, 3), (1, 3, 2), (3, 5, 3), (2, 4, 4), (2, 1, 5), (2, 5, 1) We’ll need an edge class, such as the following: static class Edge implements Comparable<Edge>{ int a, b, w; public Edge(int a, int b, int w){ this.a = a; this.b = b; this.w = w; } public int compareTo(Edge e){ // sort order is ascending, by weight // to sort in descending order, just negate the value of the compare function. return Integer.compare(w, e.w); (cid:44)→ } } Code for the edge list is as follows, using the above edge class: static int n, m; // number of nodes and edges static ArrayList<Edge> edges; CHAPTER 10. GRAPH THEORY 47 public static void main(String[] args){ n = r.nextInt(); m = r.nextInt(); edges = new ArrayList<Edge>(); for(int i = 0; i < m; i++){ // for each of the m edges int a = r.nextInt()-1; int b = r.nextInt()-1; // subtract 1 to maintain zero-indexing of vertices int w = r.nextInt(); edges.add(new Edge(a, b, w)); // add the edge to the list } Collections.sort(edges); } 10.4 Graph Traversal Algorithms Graph traversal is the process of visiting or checking each vertex in a graph. This is useful when we want to determine which vertices can be visited, whether there exists a path from one vertex to another, and so forth. There are two algorithms for graph traversal, namely depth-first search (DFS) and breadth-first search (BFS). Depth-first search Depth-first search continues down a single path to the end, then it backtracks to check other vertices. Depth-first search will process all nodes that are reachable (connected by edges) to the starting node. Let’s look at an example of how this works. Depth first-search can start at any node, but by convention we’ll start the search at node 1. We’ll use the following color scheme: blue for nodes we have already visited, red for nodes we are currently processing, and black for nodes that have not been visited yet. The DFS starts from node 1 and then goes to node 2, as it’s the only neighbor of node 1: 1 2 5 3 4 1 2 5 3 4 Now, the DFS goes to node 3 and then 4, following a single path to the end until it has no more nodes to process: CHAPTER 10. GRAPH THEORY 48 1 2 5 3 4 1 2 5 3 4 Lastly, the DFS backtracks to visit node 5, which was skipped over previously. 1 2 5 3 4 Depth-first search is implemented recursively because it allows for much simpler and shorter code. The algorithm is as follows: Algorithm: Recursive implementation for depth-first traversal of a graph Function DFS Input : start, the 0-indexed number of the starting vertex visted(start) ← true foreach vertex k adjacent to start do if visited(k) is false then DFS (k) end end Code: static void dfs(int node){ visited[node] = true; for(int next : adj[node]){ if(!visited[next]){ dfs(next); } } } Breadth-first search Breadth-first search visits nodes in order of distance away from the starting node; it first visits all nodes that are one edge away, then all nodes that are two edges away, and so on. Let’s use the same example graph that we used earlier: The BFS starts from node 1 and then goes to node 2, as it’s the only neighbor of node 1: CHAPTER 10. GRAPH THEORY 49 1 2 5 3 4 1 2 5 3 4 Now, the BFS goes to node 3, and then node 5, because both of them are two edges away from node 1: 1 2 5 3 4 1 2 5 3 4 Lastly, the BFS visits node 4, which is farthest. 1 2 5 3 4 The breadth-first search algorithm cannot be implemented recursively, so it’s significantly longer. Thus, when both BFS and DFS work, DFS is usually the better option. BFS can be used for finding the distance away from a starting node for all nodes in an unweighted graph, as we show below: CHAPTER 10. GRAPH THEORY 50 The algorithm is as follows: Algorithm: Breadth-first traversal of a graph Function BFS Input : start, the 0-indexed number of the starting vertex foreach vertex v do dist[v] ← −1 visited[v] ← false end dist[start] ← 0 Let q be a queue of integers Add start to q while q is not empty do Pop the first element from q, call it v foreach neighbor u of v do if node u has not yet been visited then dist[u] ← dist[v] + 1 Add u to q end end end Once the BFS finishes, the array dist contains the distances from the start node to each node. Example code is below. Note that the array dist[] is initially filled with −1’s to denote that none of the nodes have been processed yet. static void bfs(int k){ Arrays.fill(dist, -1); // fill distance array with -1's Queue<Integer> q = new LinkedList<Integer>(); dist[k] = 0; q.add(k); while(!q.isEmpty()){ int v = q.poll(); for(int e : adj[v]){ if(dist[e] == -1){ dist[e] = dist[v] + 1; q.add(e); } } } } CHAPTER 10. GRAPH THEORY 51 Iterative DFS If you encounter stack overflows while using recursive DFS, you can write an iterative DFS, which is just BFS but with nodes stored on a stack rather than a queue. 10.5 Floodfill Floodfill is an algorithm that identifies and labels the connected component that a particular cell belongs to, in a multi-dimensional array. Essentially, it’s DFS, but on a grid, and we want to find the connected component of all the connected cells with the same number. For example, let’s look at the following grid and see how floodfill works, starting from the top-left cell. The color scheme will be the same: red for the node currently being processed, blue for nodes already visited, and uncolored for nodes not yet visited. 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 As opposed to an explicit graph where the edges are given, a grid is an implicit graph. This means that the neighbors are just the nodes directly adjacent in the four cardinal directions. Usually, grids given in problems will be N by M , so the first line of the input contains the numbers N and M . In this example, we will use an two-dimensional integer array to store the grid, but depending on the problem, a two-dimensional character array or a two-dimensional boolean array may be more appropriate. Then, there are N rows, each with M numbers containing the contents of each square in the grid. Example input might look like the following (varies between problems): CHAPTER 10. GRAPH THEORY 52 3 4 1 1 2 1 2 3 2 1 1 3 3 3 And we’ll want to input the grid as follows: static int[][] grid; static int n, m; public static void main(String[] args){ int n = r.nextInt(); int m = r.nextInt(); grid = new int[n][m]; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ grid[i][j] = r.nextInt(); } } } When doing floodfill, we will maintain an N × M array of booleans to keep track of which squares have been visited, and a global variable to maintain the size of the current component we are visiting. Make sure to store the grid, the visited array, dimensions, and the current size variable globally. This means that we want to recursively call the search function from the squares above, below, and to the left and right of our current square. The algorithm to find the size of a connected component in a grid using floodfill is as follows (we’ll also maintain a 2d visited CHAPTER 10. GRAPH THEORY 53 array): Algorithm: Floodfill of a graph Function main // Input/output, global vars, etc hidden for i ← 0 to n − 1 do for j ← 0 to m − 1 do if the square at (i, j) is not visited then currentSize ← 0 floodfill(i, j, grid[i][j]) Process the connected component end end end Function floodfill : r, c, color Input // row and column index of starting square, target color if r or c is out of bounds then return end if the cell at (r, c) is the wrong color then return end if the square at (r, c) has already been visited then return end visited[r][c] ← true currentSize ← currentSize + 1 floodfill(r, c + 1, color) floodfill(r, c − 1, color) floodfill(r − 1, c, color) floodfill(r + 1, c, color) The code below shows the global/static variables we need to maintain while doing floodfill, and the floodfill algorithm itself. static int[][] grid; // the grid itself static int n, m; // grid dimensions, rows and columns static boolean[][] visited; // keeps track of which nodes have been visited static int currentSize = 0; // reset to 0 each time we start a new component public static void main(String[] args){ /** * input code and other problem-specific stuff here */ CHAPTER 10. GRAPH THEORY 54 for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(!visited[i][j]){ currentSize = 0; floodfill(i, j, grid[i][j]); // start a floodfill if the square hasn't already been visited, // and then store or otherwise use the component size // for whatever it's needed for } } } } static void floodfill(int r, int c, int color){ if(r < 0 || r >= n || c < 0 || c >= m) return; // if outside grid if(grid[r][c] != color) return; // wrong color if(visited[r][c]) return; // already visited this square visited[r][c] = true; // mark current square as visited currentSize++; // increment the size for each square we visit // recursively call floodfill for neighboring squares floodfill(r, c+1, color); floodfill(r, c-1, color); floodfill(r-1, c, color); floodfill(r+1, c, color); } 10.6 Disjoint-Set Data Structure Let’s say we want to construct a graph, one edge at a time. We also want to be able to add additional nodes, and query whether two nodes are connected. We can naively solve this problem by adding the edges and running a floodfill each time, before finally checking whether two nodes have the same color. This yields a time complexity of O(nm) for a graph of n nodes and m edges. However, we can do better than this using a data structure known as Disjoint-Set Union, or DSU for short. This data structure supports two operations: • Add an edge between two nodes. • Check if two nodes are connected. To achieve this, we store sets as trees, with the root of the tree representing the “parent” of the set. Initially, we store each node as its own set. Then, we combine their sets when we add an edge between two nodes. The image below illustrates this structure. CHAPTER 10. GRAPH THEORY 55 In this graph, 1 is the parent of the set containing 3, 2, and 4. To implement this, let’s store the parent of each node in the tree represented by that node’s set. Then, to merge two sets, we set the parent of one tree’s root to the other tree’s root, like so: The following methods demonstrate this idea: static int[] parent; //stores the parent nodes static void initialize(int N){ for(int i = 0; i < N; i++){ parent[i] = i; //initially, the root of each set is the node itself } } static int find(int x){ //finds the root of the set of x if(x == parent[x]){ //if x is the parent of itself, it is the root return x; } else{ return find(parent[x]); //otherwise, recurse to the parent of x } CHAPTER 10. GRAPH THEORY 56 } static void union(int a, int b){ //merges the sets of a and b int c = find(a); //find the root of a int d = find(b); //find the root of b if(c != d){ parent[d] = c; //merge the sets by setting the parent of d to c } } However, this naive implementation of a DSU isn’t much better than simply running a floodfill. As the recursing up the tree of a set to find it’s root can be time-consuming for trees with long chains, the runtime ultimately degrades to still being O(nm) for n nodes and m edges. Now that we understand the general idea of a DSU, we can improve the runtime of this implementation using an optimization known as path compression. The general idea is to reassign nodes in the tree as you are recursively calling the find method to prevent long chains from forming. Here is a rewritten find method representing this idea: static int find(int x){ if(x == parent[x]){ return x; } else{ // we set the direct parent to the root of the set to reduce path length return parent[x] = find(parent[x]); } } The following image demonstrates how the tree with parent 1 is compressed after find(6) is called. All of the bolded nodes in the final tree were visited during the recursive operation, and now point to the root. CHAPTER 10. GRAPH THEORY 57 With this new optimization, the runtime reduces to O(n log n), far better than our naive algorithm. Further optimizations can reduce the runtime of DSU to nearly constant. However, those techniques and the proof of complexity for these optimizations are both unnecessary for and out of the scope of the USACO Silver division, so they will not be included in this book. 10.7 Bipartite Graphs A bipartite graph is a graph such that each node can be colored in one of two colors, such that no two adjacent nodes have the same color. For example, the following graph is bipartite: 1 2 4 3 5 A graph is bipartite if and only if there are no cycles of odd length. For example, the following graph is not bipartite, because it contains a cycle of length 3. 1 3 2 4 The following image depicts how a bipartite graph splits vertices into two “groups” depending on their color. CHAPTER 10. GRAPH THEORY 58 In order to check whether a graph is bipartite, we use a modified breadth-first search. Algorithm: Bipartiteness check Function bipartite : a graph Input Output : whether the graph is bipartite or not Assign color 1 to the starting vertex // Use the following modified bfs foreach vertex v processed in bfs do d ← dist(start, v) if d is odd then Assign color 2 to vertex v else Assign color 1 to vertex v end foreach vertex w adjacent to v do if w and v are the same color then return false // not bipartite end end end return true // bipartite 10.8 Problems DFS/BFS Problems 1. USACO January 2018 Silver Problem 3: MooTube http://www.usaco.org/index.php?page=viewproblem2&cpid=788 CHAPTER 10. GRAPH THEORY 59 2. USACO December 2016 Silver Problem 3: Moocast http://www.usaco.org/index.php?page=viewproblem2&cpid=668 3. USACO US Open 2016 Silver Problem 3: Closing the Farm http://www.usaco.org/index.php?page=viewproblem2&cpid=644 DSU Problems Many of these problems do not require DSU. However, they become much easier to do if you understand it. 4. USACO US Open Silver Problem 3: The Moo Particle http://usaco.org/index.php?page=viewproblem2&cpid=1040 5. USACO January 2018 Silver Problem 3: MooTube http://www.usaco.org/index.php?page=viewproblem2&cpid=788 6. USACO December 2019 December Problem 3: Milk Visits http://usaco.org/index.php?page=viewproblem2&cpid=968 7. USACO US Open 2016 Gold Problem 2: Closing the Farm http://www.usaco.org/index.php?page=viewproblem2&cpid=646 8. USACO January Contest 2020 Silver Problem 3: Wormhole Sort http://www.usaco.org/index.php?page=viewproblem2&cpid=992 Other Graph Problems 9. (Bipartite Graphs) USACO February 2019 Silver Problem 3: The Great Revegetation http://www.usaco.org/index.php?page=viewproblem2&cpid=920 10. CodeForces Round 595 (Div. 3) Problem B2: Books Exchange https://codeforces.com/problemset/problem/1249/B2 Chapter 11 Prefix Sums 11.1 Prefix Sums Let’s say we have an integer array arr with N elements, and we want to process Q queries to find the sum of the elements between two indices a and b, inclusive, with different values of a and b for every query. For the purposes of this chapter, we will assume that the original array is 1-indexed, meaning arr[0] = 0 (which is a dummy index), and the actual array elements occupy indices 1 through N (this means that the array actually has length N + 1). Let’s use the following example 1-indexed array arr, with N = 6: Index i arr[i] 0 0 1 1 2 6 3 4 4 2 5 5 6 3 Naively, for every query, we can iterate through all entries from index a to index b to add them up. Since we have Q queries and each query requires a maximum of O(N ) operations to calculate the sum, our total time complexity is O(N Q). For most problems of this nature, the constraints will be N, Q ≤ 105, so N Q is on the order of 1010. This is not acceptable; it will almost always exceed the time limit. Instead, we can use prefix sums to process these array sum queries. We designate a prefix sum array prefix[]. First, since we’re 1-indexing the array, set prefix[0] = 0, then for indices k such that 1 ≤ k ≤ n, define the prefix sum array as follows: prefix[k] = k (cid:88) i=1 arr[i] Basically, what this means is that the element at index k of the prefix sum array stores the sum of all the elements in the original array from index 1 up to k. This can be calculated easily in O(N ) by the following formula: prefix[k] = prefix[k-1] + arr[k] For the example case, our prefix sum array looks like this: Index i prefix[i] 0 0 1 1 2 7 3 11 4 13 5 18 6 21 60 CHAPTER 11. PREFIX SUMS 61 Now, when we want to query for the sum of the elements of arr between (1-indexed) indices a and b inclusive, we can use the following formula: b (cid:88) i=a arr[i] = b (cid:88) i=1 arr[i] − a−1 (cid:88) i=1 arr[i] Using our definition of the elements in the prefix sum array, we have b (cid:88) i=a arr[i] = prefix[b] − prefix[a-1] Since we are only querying two elements in the prefix sum array, we can calculate subarray sums in O(1) per query, which is much better than the O(N ) per query that we had before. Now, after an O(N ) preprocessing to calculate the prefix sum array, each of the Q queries takes O(1) time. Thus, our total time complexity is O(N + Q), which should now pass the time limit. Let’s do an example query and find the subarray sum between indices a = 2 and b = 5, inclusive, in the 1-indexed arr. From looking at the original array, we see that this is (cid:80)5 i=2 arr[i] = 6 + 4 + 2 + 5 = 17. Index i arr[i] 0 0 1 1 2 6 3 4 4 2 5 5 6 3 Using prefix sums: prefix[5] − prefix[1] = 18 − 1 = 17. Index i prefix[i] 0 0 1 1 2 7 3 11 4 13 5 18 6 21 11.2 Two Dimensional Prefix Sums Now, what if we wanted to process Q queries for the sum over a subrectangle of a N rows by M columns matrix in two dimensions? Let’s assume both rows and columns are 1-indexed, and we use the following matrix as an example: 0 0 0 0 0 0 1 1 4 7 0 5 7 6 5 0 6 11 1 4 0 11 9 3 2 0 8 4 2 3 Naively, each sum query would then take O(N M ) time, for a total of O(QN M ). This is too slow. Let’s take the following example region, which we want to sum: CHAPTER 11. PREFIX SUMS 62 0 0 0 0 0 0 1 1 4 7 0 5 7 6 5 0 6 11 1 4 0 11 9 3 2 0 8 4 2 3 Manually summing all the cells, we have a submatrix sum of 7 + 11 + 9 + 6 + 1 + 3 = 37. The first logical optimization would be to do one-dimensional prefix sums of each row. Then, we’d have the following row-prefix sum matrix. The desired subarray sum of each row in our desired region is simply the green cell minus the red cell in that respective row. We do this for each row, to get (28 − 1) + (14 − 4) = 37. 0 0 0 0 0 0 1 1 4 7 0 6 8 10 12 0 12 19 11 16 0 23 28 14 18 0 31 32 16 21 Now, if we wanted to find a submatrix sum, we could break up the submatrix into a subarray for each row, and then add their sums, which would be calculated using the prefix sums method described earlier. Since the matrix has N rows, the time complexity of this is O(QN ). This is better, but still usually not fast enough. To do better, we can do two-dimensional prefix sums. In our two dimensional prefix sum array, we have prefix[a][b] = a (cid:88) b (cid:88) i=1 j=1 arr[i][j] This can be calculated as follows for row index 1 ≤ i ≤ n and column index 1 ≤ j ≤ m: prefix[i][j] = prefix[i-1][j] + prefix[i][j-1] − prefix[i-1][j-1] + arr[i][j] The submatrix sum between rows a and A and columns b and B, can thus be expressed as follows: A (cid:88) B (cid:88) arr[i][j] = prefix[A][B] − prefix[a-1][B] i=a j=b − prefix[A][b-1] + prefix[a-1][b-1] Summing the blue region from above using the 2d prefix sums method, we add the value of the green square, subtract the values of the red squares, and then add the value of the gray square. In this example, we have 65 − 23 − 6 + 1 = 37, as expected. 0 0 0 0 0 0 1 2 6 13 0 6 14 24 36 0 12 31 42 58 0 23 51 65 83 0 31 63 79 100 Since no matter the size of the submatrix we are summing, we only need to access 4 values of the 2d prefix sum array, this runs in O(1) per query after an O(N M ) preprocessing. This is fast enough. CHAPTER 11. PREFIX SUMS 11.3 Problems 63 1. USACO December 2015 Silver Problem 3: Breed Counting http://usaco.org/index.php?page=viewproblem2&cpid=572 2. USACO January 2016 Silver Problem 2: Subsequences Summing to Sevens http://usaco.org/index.php?page=viewproblem2&cpid=595 3. USACO December 2017 Silver Problem 1: My Cow Ate My Homework http://www.usaco.org/index.php?page=viewproblem2&cpid=762 4. USACO January 2017 Silver Problem 2: Hoof, Paper, Scissors http://www.usaco.org/index.php?page=viewproblem2&cpid=691 5. (2D Prefix Sums) USACO February 2019 Silver Problem 2: Painting the Barn http://www.usaco.org/index.php?page=viewproblem2&cpid=919 Chapter 12 Binary Search 12.1 Binary Search on the Answer You’re probably already familiar with the concept of binary searching for a number in a sorted array. However, binary search can be extended to binary searching on the answer itself. When we binary search on the answer, we start with a search space, where we know the answer lies in. Then, each iteration of the binary search cuts the search space in half, so the algorithm tests O(log N ) values, which is efficient and much better than testing each possible value in the search space. Similarly to how binary search on an array only works on a sorted array, binary search on the answer only works if the answer function is monotonic. Let’s say we have a function check(x) that returns true if the answer of x is possible, and false otherwise. Usually, in such problems, we’ll want to find the maximum or minimum value of x such that check(x) is true. In order for binary search to work, the search space must look like something of the following form, using a check function as we described above. true true true true true false false false false Then, we find the point at which true becomes false, using binary search. Below, we present two algorithms for binary search. The first implementation may be more intuitive, because it’s closer to the binary search most students learned, while the 64 CHAPTER 12. BINARY SEARCH 65 second implementation is shorter. Algorithm: Binary searching for the answer Function binarySearch1 left ← lower bound of search space right ← upper bound of search space ans ← −1 while left ≤ right do mid ← (left + right)/2 if check(mid) then left ← mid + 1 ans ← mid else right ← mid − 1 end return ans Algorithm: Binary searching for the answer Function binarySearch2 pos ← 0 max ← upper bound of search space for (a = max; a ≥ 1; a /= 2) do while check(pos + a) do pos ← pos + a end end return pos 12.2 Example Source: Codeforces Round 577 (Div. 2) Problem C https://codeforces.com/contest/1201/problem/C Given an array arr of n integers, where n is odd, we can perform the following operation on it k times: take any element of the array and increase it by 1. We want to make the median of the array as large as possible, after k operations. Constraints: 1 ≤ n ≤ 2 · 105, 1 ≤ k ≤ 109 and n is odd. The solution is as follows: we first sort the array in ascending order. Then, we binary search for the maximum possible median. We know that the number of operations required to raise the median to x increases monotonically as x increases, so we can use binary search. For a given median value x, the number of operations required to raise the median to x is n (cid:88) i=(n+1)/2 max(0, x − arr[i]) CHAPTER 12. BINARY SEARCH 66 If this value is less than or equal to k, then x can be the median, so our check function returns true. Otherwise, x cannot be the median, so our check function returns false. Solution code (using the second implementation of binary search): static int n; static long k; static long[] arr; public static void main(String[] args) { n = r.nextInt(); k = r.nextLong(); arr = new long[n]; for(int i = 0; i < n; i++){ arr[i] = r.nextLong(); } Arrays.sort(arr); pw.println(search()); pw.close(); } // binary searches for the correct answer static long search(){ long pos = 0; long max = (long)2E9; for(long a = max; a >= 1; a /= 2){ while(check(pos+a)) pos += a; } return pos; } // checks whether the number of given operations is sufficient // to raise the median of the array to x static boolean check(long x){ long operationsNeeded = 0; for(int i = (n-1)/2; i < n; i++){ operationsNeeded += Math.max(0, x-arr[i]); } if(operationsNeeded <= k){ return true; } else{ return false; } } 12.3 Problems 1. USACO December 2018 Silver Problem 1: Convention http://www.usaco.org/index.php?page=viewproblem2&cpid=858 CHAPTER 12. BINARY SEARCH 67 2. USACO January 2016 Silver Problem 1: Angry Cows http://usaco.org/index.php?page=viewproblem2&cpid=594 3. USACO January 2017 Silver Problem 1: Cow Dance Show http://www.usaco.org/index.php?page=viewproblem2&cpid=690 4. Educational Codeforces Round 60 Problem C: Magic Ship https://codeforces.com/problemset/problem/1117/C (Also uses prefix sums) 5. USACO January 2020 Silver Problem 2: Loan Repayment http://www.usaco.org/index.php?page=viewproblem2&cpid=991 (Warning: extremely difficult for silver) Chapter 13 Elementary Number Theory 13.1 Prime Factorization A number a is called a divisor or a factor of a number b if b is divisible by a, which means that there exists some integer k such that b = ka. Conventionally, 1 and n are considered divisors of n. A number n > 1 is prime if its only divisors are 1 and n. Numbers greater than 1 that are not prime are composite. Every number has a unique prime factorization: a way of decomposing it into a product of primes, as follows: n = p1 a1p2 a2 · · · pk ak where the pi are distinct primes and the ai are positive integers. Now, we will discuss how to find the prime factorization of an integer. Algorithm: Finds the prime factorization of a number Function factor : n, the number to be factorized Input Output : v, a list of all the prime factors v ← empty list for i ← 2 to (cid:98) n(cid:99) do √ while n is divisible by i do n ← n/i Add i to the list v end end return v ; √ √ This algorithm runs in O( n) time, because the for loop checks divisibility for at most n values. Even though there is a while loop inside the for loop, dividing n by i quickly reduces the value of n, which means that the outer for loop runs less iterations, which actually speeds up the code. 68 CHAPTER 13. ELEMENTARY NUMBER THEORY 69 Let’s look at an example of how this algorithm works, for n = 252. i n 2 252 2 126 63 2 21 3 7 3 v {} {2} {2, 2} {2, 2, 3} {2, 2, 3, 3} At this point, the for loop terminates, because i is already 3 which is greater than (cid:98) 7(cid:99). In the last step, we add 7 to the list of factors v, because it otherwise won’t be added, for a final prime factorization of {2, 2, 3, 3, 7}. √ 13.2 GCD and LCM The greatest common divisor (GCD) of two integers a and b is the largest integer that is a factor of both a and b. In order to find the GCD of two numbers, we use the Euclidean Algorithm, which is as follows: gcd(a, b) = (cid:40) a gcd(b, a mod b) b = 0 b (cid:54)= 0 This algorithm is very easy to implement using a recursive function, as follows: public int gcd(int a, int b){ if(b == 0) return a; return gcd(b, a % b); } Finding the GCD of two numbers can be done in O(log n) time, where n = min(a, b). The least common multiple (LCM) of two integers a and b is the smallest integer divisible by both a and b. The LCM can easily be calculated from the following property with the GCD: lcm(a, b) = a · b gcd(a, b) If we want to take the GCD or LCM of more than two elements, we can do so two at a time, in any order. For example, gcd(a1, a2, a3, a4) = gcd(a1, gcd(a2, gcd(a3, a4))) CHAPTER 13. ELEMENTARY NUMBER THEORY 70 13.3 Modular Arithmetic In modular arithmetic, instead of working with integers themselves, we work with their remainders when divided by m. We call this taking modulo m. For example, if we take m = 23, then instead of working with x = 247, we use x mod 23 = 17. Usually, m will be a large prime, given in the problem; the two most common values are 109 + 7, and 998 244 353. Modular arithmetic is used to avoid dealing with numbers that overflow built-in data types, because we can take remainders, according to the following formulas: (a + b) mod m = (a mod m + b mod m) mod m (a − b) mod m = (a mod m − b mod m) mod m (a · b) (mod m) = ((a mod m) · (b mod m)) mod m ab mod m = (a mod m)b mod m Under a prime moduli, division does exist; however it’s rarely used in problems and is beyond the scope of this book. 13.4 Problems 1. CodeForces VK Cup 2012 Wildcard Round 1 https://codeforces.com/problemset/problem/162/C Chapter 14 Additional Silver Topics 14.1 Two Pointers The two pointers method iterates two pointers across an array, to track the start and end of an interval, or two values in a sorted array that we are currently checking. Both pointers are monotonic; meaning each pointer starts at one end of the array and only move in one direction. 2SUM Problem Given an array of N elements (1 ≤ N ≤ 105), find two elements that sum to X. We can solve this problem using two pointers; sort the array, then set one pointer at the beginning and one pointer at the end of the array. Then, we consider the sum of the numbers at the indices of the pointers. If the sum is too small, advance the left pointer towards the right, and if the sum is too large, advance the right pointer towards the left. Repeat until either the correct sum is found, or the pointers meet (in which case there is no solution). Let’s take the following example array, where N = 6 and X = 15 First, we sort the array: 1 7 11 10 5 13 1 5 7 10 11 13 We then place the left pointer at the start of the array, and the right pointer at the end of the array. 1 5 7 10 11 13 Then, run and repeat this process: If the sum of the pointer elements is less than X, move the left pointer one step to the right. If the sum is greater than X, move the right pointer one step to the left. The example is as follows. First, the sum 1 + 13 = 14 is too small, so we move the left pointer one step to the right. 1 5 7 10 11 13 71 CHAPTER 14. ADDITIONAL SILVER TOPICS 72 Now, 5 + 13 = 18 overshoots the sum we want, so we move the right pointer one step to the left. 1 5 7 10 11 13 At this point we have 5 + 11 = 16, still too big. We continue moving the right pointer to the left. 1 5 7 10 11 13 Now, we have the correct sum, and we are done. Code is as follows: int left = 0; int right = n-1; while(left < right){ if(arr[left] + arr[right] == x){ break; } else if(arr[left] + arr[right] < x){ left++; } else { right--; } } // if left >= right after the loop ends, no answer exists. Subarray Sum Given an array of N (1 ≤ N ≤ 105) positive elements, find a contiguous subarray that sums to X. We can do this in a similar manner to how we did the 2SUM problem: except this time we start both pointers at the left, and the pointers mark the beginning and end of the subarray we are currently checking. We advance the right pointer one step to the right if the total of the current subarray is too small, advance the left pointer one step to the right if the current total is too large, and we are done when we find the correct total. Maximum subarray sum Another problem that isn’t quite solved by two pointers, but is somewhat related, is the maximum subarray sum problem. Given an array of N integers (1 ≤ N ≤ 105), which can be positive or negative, find the maximum sum of a contiguous subarray. We can solve this problem using Kadane’s algorithm, which works as follows: we iterate through the elements of the array, and for each index i, we maintain the maximum subarray sum of a subarray ending at i in the variable current, and the maximum subarray sum of a subarray ending at or before i, in the variable best. Example code is below. CHAPTER 14. ADDITIONAL SILVER TOPICS 73 int best = 0; int current = 0; for(int i = 0; i < n; i++){ current = Math.max(0, current + arr[i]); best = Math.max(best, current); } 14.2 Line Sweep Line sweep is the technique of sorting a set of points or line segments and then processing them in order (this usually means from left to right). The name line sweep comes from the fact that we are sweeping an imaginary vertical line across the plane containing the points or segments. To describe this technique, we’ll be using the 2019 US Open problem, “Cow Steeplechase II”. http://usaco.org/index.php?page=viewproblem2&cpid=943 In this problem, we are given some line segments and asked to find one line segment and remove it such that the resulting segments form no intersections. It is guaranteed that this is always possible. First of all, let’s observe it is sufficient to find any two line segments that intersect. Once we have done this, the solution is guaranteed to be one of these two segments. Then, out of the two, the segment with multiple intersections is the answer (because removing any other segment decreases the number of intersections by at most 1, and only removing the segment with multiple intersections ensures there are no intersections). If both segments have one intersection, that means the intersect with each other, so we should return the one with the smallest index (as per the problem statement). Now, the problem reduces to two parts: checking if two line segments intersect, and processing the line segments using a line sweep. Checking If Two Segments Intersect To check if two line segments intersect, we will use a fact from algebra: if we have the points A = (xa, ya), B = (xb, yb), and C = (xc, yc), then the (signed) area of (cid:52)ABC, denoted [ABC], is (xb − xa)(yc − ya) − (xc − xa)(yb − ya). This can be derived from the cross product of the vectors −→ AB and −→ AC. The part that will help us is the fact that this area is signed, which means that [ABC] is positive if A, B, and C occur in counterclockwise order, negative if A, B, and C occur in clockwise order, and zero if A, B, and C are collinear. Then, the key observation is that two segments P Q and XY intersect if the two conditions hold: CHAPTER 14. ADDITIONAL SILVER TOPICS 74 • [XP Q] and [Y P Q] have different signs • [P XY ] and [QXY ] have different signs For example, in the figure below, [X1P1Q1] and [Q1X1Y1] are positive because their vertices occur in counterclockwise order, and [Y1P1Q1] and [P1X1Y1] are negative because their vertices occur in clockwise order. Therefore, we know that X1Y1 and P1Q1 intersect. Similarly, on the right, we know that [P2X2Y2] and [Q2X2Y2] have vertices both going in clockwise order, so their signed areas are the same, and therefore P2Q2 and X2Y2 don’t intersect. X1 P1 Q1 P2 X2 Q2 Y1 Y2 If the two conditions hold and some of the signs are zero, then this means that the segments intersect at their endpoints. If the problem does not count these as intersecting, then consider zero to have the same sign as both positive and negative. However, there is a special case. If the signs of all four areas are zero, then all four points lie on a line. To check if they intersect in this case, we just check whether one point is between the others. In particular, we check if P or Q is on XY or if X is on P Q. We don’t need to check if Y is on P Q because if the segments do intersect, we will have two instances of points on the other segments. Here’s a full implementation: public class Point { public int x, y; public Point(int x, int y){ this.x = x; this.y = y; } } public static int sign(Point A, Point B, Point C) { int area = (B.x-A.x) * (C.y-A.y) - (C.x-A.x) * (B.y-A.y); if (area > 0) return 1; if (area < 0) return -1; return 0; } public static boolean between(Point P, Point X, Point Y) { return ((X.x <= P.x && P.x <= Y.x) || (Y.x <= P.x && P.x <= X.x)) && ((X.y <= P.y && P.y <= Y.y) || (Y.y <= P.y && P.y <= X.y)); CHAPTER 14. ADDITIONAL SILVER TOPICS 75 } public static boolean intersectQ(Point P, Point Q, Point X, Point Y) { int[] signs = {sign(P, X, Y), sign(Q, X, Y), sign(X, P, Q), sign(Y, P, Q)}; if (signs[0] == 0 && signs[1] == 0 && signs[2] == 0 && signs[3] == 0) return between(P, X, Y) || between(Q, X, Y) || between(X, P, Q); return signs[0] != signs[1] && signs[2] != sign[3]; } Processing Line Segments Let’s break apart the N line segments into 2N events, one for each start and end point. We’ll store whether some event is a start point or an end point, and which start points correspond to each end point. Then, we process the endpoints in order of x coordinate from left to right, maintaining a set of currently processed segments, which is sorted by y. When we hit an endpoint, we either add or remove a segment from the set, depending on whether we start or end a segment. Every time we add a segment, we check it for intersection with the segment above it and the segment below it. In addition, every time we remove a segment, we check the segment above it and the segment below it for intersection. Once we find an intersection, we are done. 14.3 Bitwise Operations and Subsets Binary Representations of Integers In programming, numbers are stored as binary representations. This means that a number x is represented as n (cid:88) ai2i, x = i=0 where the ais are either 0 or 1 and n = (cid:98)log2 x(cid:99). For example: 17 = 24 + 20 = 100012 Each digit in the binary representation, which is either 0 or 1, is called a bit. Bitwise Operations There are several binary operations on binary numbers called bitwise operations. These operations are applied separately for each bit position. The common binary operations are shown in table 14.1: CHAPTER 14. ADDITIONAL SILVER TOPICS 76 Bit A Bit B A and B A or B A xor B 1 1 0 0 1 0 1 0 1 0 0 0 1 1 1 0 0 1 1 0 Table 14.1: The outputs of bitwise operations on two bits The AND operation (&) returns 1 if and only if both bits are 1. 19 & 27 1 0 0 1 1 = 19 AN D 1 1 0 1 1 = 27 1 0 0 1 1 = 19 = The OR operation (|) returns 1 if either bit is 1. 19 | 27 1 0 0 1 1 = 19 OR 1 1 0 1 1 = 27 = 1 1 0 1 1 = 27 The XOR operation (∧) returns 1 if and only if exactly one of the bits is 1. 19 ∧ 26 1 0 0 1 1 = 19 XOR 1 1 0 1 1 = 27 0 1 0 0 0 = 8 = Finally, the left shift operator x << k multiplies x by 2k. Watch for overflow and use the long data type if necessary. For example: 1 << 5 = 1 · 25 = 32 7 << 2 = 7 · 22 = 28 Exercises Calculate by converting the numbers to binary, applying the bit operations, and then converting back to decimal numbers: (a) 19 & 34 (b) 14 | 29 (c) 10 ∧ 19 (d) 3 << 5 Answer: 2 Answer: 31 Answer: 25 Answer: 96 CHAPTER 14. ADDITIONAL SILVER TOPICS 77 Generating Subsets Occasionally in a problem we’ll want to iterate through every possible subset of a given set, either to find a subset that satisfies some condition, or to find the number of subsets that satisfy some condition. Also, some problems might ask you to find the number of partitions of a set into 2 groups that satisfy a certain condition. In this case, we will iterate through all possible subsets, and check each subset for validity (first adding the non-selected elements to the second subset if necessary). In a set of N elements, there are 2N possible subsets, because for each of the N elements, there are two choices: either in the subset, or not in the subset. Subset problems usually require a time complexity of O(N · 2N ), because each subset has an average of O(N ) elements. Now, let’s look at how we can generate the subsets. We can represent subsets as binary numbers from 0 to 2N − 1. Then, each bit represents whether or not a certain element is in the subset. Let’s look at an example set of a, b, c. number binary subset 0 1 2 3 4 5 6 7 000 001 010 011 100 101 110 111 { } {a} {b} {a, b} {c} {a, c} {b, c} {a, b, c} Algorithm: The algorithm for generating all subsets of a given input array Function generateSubsets Input : An array arr, and its length n for i ← 0 to 2n − 1 do Declare list for j = 0 to n-1 do if the bit in the binary representation of i corresponding to 2j is 1 then Add arr[j] to the list end end Process the list end In the following code, our original set is represented by the array arr[] with length n. int ans = 0; for(int i = 0; i < (1<<n); i++){ // this loop iterates through the 2^n subsets, one by one. // 1 << n is a shortcut for 2^n CHAPTER 14. ADDITIONAL SILVER TOPICS 78 ArrayList<Integer> list = new ArrayList<Integer>(); // we create a new list for each subset and add // the elements to it for(int j = 0; j < n; j++){ if((i & (1 << j)) > 0){ // (1 << j) is the number where only the bit representing 2^j is 1. list.add(arr[j]); // if the respective bit of i is 1, // add that element to the list } } if(valid(list)){ // code is not included here, but this method will vary depending on the // problem to check if a certain subset is valid // and increments the answer counter if so. ans++; } } 14.4 Ad-hoc Problems The silver division also often has ad hoc problems. They primarily rely on non-standard algorithmic thinking and problem solving ability. You develop these skills by solving problems; thus, we don’t have much content to teach you about ad hoc problems, but we provide a selection of problems at the end of the chapter for your practice. 14.5 Problems Two Pointers 1. CSES Problem Set Task 1640: Sum of Two Values https://cses.fi/problemset/task/1640 2. CSES Problem Set Task 1643: Maximum Subarray Sum https://cses.fi/problemset/task/1643 Line Sweep 3. USACO US Open 2019 Silver Problem 2: Cow Steeplechase II http://usaco.org/index.php?page=viewproblem2&cpid=943 Subsets 4. (Subsets) CSES Problem Set Task 1623: Apple Division https://cses.fi/problemset/task/1623 CHAPTER 14. ADDITIONAL SILVER TOPICS 79 Ad hoc problems 5. USACO February 2016 Silver Problem 1: Circular Barn http://usaco.org/index.php?page=viewproblem2&cpid=618 6. USACO US Open 2019 Silver Problem 1: Left Out http://www.usaco.org/index.php?page=viewproblem2&cpid=942 7. USACO February 2019 Silver Problem 1: Sleepy Cow Herding http://www.usaco.org/index.php?page=viewproblem2&cpid=918 8. USACO January 2017 Silver Problem 3: Secret Cow Code http://www.usaco.org/index.php?page=viewproblem2&cpid=692 9. USACO January 2020 Silver Problem 1: Berry Picking http://www.usaco.org/index.php?page=viewproblem2&cpid=990 10. USACO December 2019 Silver Problem 2: Meetings http://www.usaco.org/index.php?page=viewproblem2&cpid=967 (Warning: extremely difficult) Part IV Problem Set 80 Chapter 15 Parting Shots You improve at competitive programming primarily by doing problems, so we leave you with an extensive selection of CodeForces problems for your practice. This consists of five problem sets of ten problems each, increasing in difficulty. The problems mostly use topics covered in the book, but may require some ingenuity to find the solution. If you get stuck, you can search for the editorial. Best of luck! Set 1 1. https://codeforces.com/problemset/problem/1227/B 2. https://codeforces.com/problemset/problem/1196/B 3. https://codeforces.com/problemset/problem/1195/B 4. https://codeforces.com/problemset/problem/1294/B 5. https://codeforces.com/problemset/problem/1288/B 6. https://codeforces.com/problemset/problem/1293/A 7. https://codeforces.com/problemset/problem/1213/B 8. https://codeforces.com/problemset/problem/1207/B 9. https://codeforces.com/problemset/problem/1324/B 10. https://codeforces.com/problemset/problem/1327/A Set 2 1. https://codeforces.com/problemset/problem/1182/B 2. https://codeforces.com/problemset/problem/1183/D 3. https://codeforces.com/problemset/problem/1183/C 4. https://codeforces.com/problemset/problem/1133/C 81 CHAPTER 15. PARTING SHOTS 82 5. https://codeforces.com/problemset/problem/1249/B2 6. https://codeforces.com/problemset/problem/1194/B 7. https://codeforces.com/problemset/problem/1271/C 8. https://codeforces.com/problemset/problem/1326/C 9. https://codeforces.com/problemset/problem/1294/C 10. https://codeforces.com/problemset/problem/1272/B Set 3 1. https://codeforces.com/problemset/problem/1169/B 2. https://codeforces.com/problemset/problem/1102/D 3. https://codeforces.com/problemset/problem/978/F 4. https://codeforces.com/problemset/problem/1196/C 5. https://codeforces.com/problemset/problem/1154/D 6. https://codeforces.com/problemset/problem/1272/D 7. https://codeforces.com/problemset/problem/1304/C 8. https://codeforces.com/problemset/problem/1296/C 9. https://codeforces.com/contest/1263/problem/D 10. https://codeforces.com/contest/1339/problem/C Set 4 1. https://codeforces.com/problemset/problem/1281/B 2. https://codeforces.com/problemset/problem/1196/D2 3. https://codeforces.com/problemset/problem/1165/D 4. https://codeforces.com/problemset/problem/1238/C 5. https://codeforces.com/problemset/problem/1234/D 6. https://codeforces.com/problemset/problem/1198/B 7. https://codeforces.com/problemset/problem/1198/A 8. https://codeforces.com/problemset/problem/1077/D 9. https://codeforces.com/problemset/problem/1303/C 10. https://codeforces.com/problemset/problem/1098/A CHAPTER 15. PARTING SHOTS 83 Set 5 1. https://codeforces.com/problemset/problem/1185/D 2. https://codeforces.com/problemset/problem/1195/D2 3. https://codeforces.com/problemset/problem/1154/E 4. https://codeforces.com/contest/1195/problem/C 5. https://codeforces.com/problemset/problem/1196/E 6. https://codeforces.com/problemset/problem/1328/D 7. https://codeforces.com/problemset/problem/1253/D 8. https://codeforces.com/problemset/problem/1157/E 9. https://codeforces.com/problemset/problem/1185/C2 10. https://codeforces.com/problemset/problem/1209/D |