Art of Programming Contest SE For Uva PDF
Art of Programming Contest SE For Uva PDF
CS3233
CompetitiveProgramming
p
g
g
Dr.StevenHalim
Dr.
Steven Halim
Week02 DataStructures&Libraries
FocusonBitManipulation&BinaryIndexedTree
CS3233 CompetitiveProgramming,
StevenHalim,SoC,NUS
Outline
MiniContest1+Break(discussionofA/B)
/
SomeAdmins
DataStructuresWithBuiltinLibraries
Justaquickwalkthrough
Read/experimentwiththedetailsonyourown
Read/experiment with the details on your own
LinearDataStructures(CS1010/1st halfofCS2020)
nd halfofCS2020))
NonLinearDataStructures(CS2010/2
(
Focusontheredhighlights
LINEARDATASTRUCTURES
WITHBUILTINLIBRARIES
CS3233 CompetitiveProgramming,
StevenHalim,SoC,NUS
I am
Iam
1. ApureCcoder
2. ApureC++coder
A pure C++ coder
3. Amixbetween
C/C
C/C++coder
d
4. ApureJavacoder
p
5. Amultilingual
coder:C/C++/Java
d C/C++/J
0
0 of 120
CS3233 CompetitiveProgramming,
1
StevenHalim,SoC,NUS
0
5
Thereare2verycommonoperationsonArray:
There are 2 very common operations on Array:
Sorting
Searching
S
hi
Letstakealookatefficientwaystodothem
CS3233 CompetitiveProgramming,
StevenHalim,SoC,NUS
Two fundamental
Two
fundamental CSproblems
CS problems
SORTING+SEARCHING
INVOLVINGARRAY
CS3233 CompetitiveProgramming,
StevenHalim,SoC,NUS
Sorting (1)
Sorting(1)
Definition:
Givenunsortedstuffs,sortthem*
,
PopularSortingAlgorithms
O(n
O( 2)algorithms:Bubble/Selection/InsertionSort
) l ih
B bbl /S l i /I
i S
O(nlogn)algorithms:Merge/Quick^/HeapSort
Specialpurpose:Counting/Radix/BucketSort
Reference:
http://en.wikipedia.org/wiki/Sorting_algorithm
CS3233 CompetitiveProgramming,
StevenHalim,SoC,NUS
Sorting (2)
Sorting(2)
InICPC,youcanforgetallthese
Ingeneral,ifyouneedtosortsomething,
g
, y
g ,
justusetheO(nlogn)sortinglibrary:
C
C++STLalgorithm::sort
STL algorithm:: sort
JavaCollections.sort
In
InICPC,sortingiseitherusedaspreliminarystep
ICPC sorting is either used as preliminary step
formorecomplexalgorithmortobeautifyoutput
Familiaritywithsortinglibrariesisamust!
Familiarity with sorting libraries is a must!
CS3233 CompetitiveProgramming,
StevenHalim,SoC,NUS
Sorting (3)
Sorting(3)
SortingroutinesinC++STLalgorithm
sort abugfreeimplementationofintrosort*
g
p
Fast,itrunsinO(nlogn)
Cansortbasicdatatypes(ints,doubles,chars),Abstract
Can sort basic data types (ints, doubles, chars), Abstract
DataTypes(C++class),multifieldsorting(2criteria)
partial_sort
partial sort implementationofheapsort
implementation of heapsort
CandoO(klogn)sorting,ifwejustneedtopksorted!
stable_sort
stable sort
Ifyouneedtohavethesortingstable,keyswithsame
values appear in the same order as in input
valuesappearinthesameorderasininput
CS3233 CompetitiveProgramming,
StevenHalim,SoC,NUS
Searching in Array
SearchinginArray
Twovariants:
Whenthearrayissortedversusnotsorted
y
MustdoO(n)linearscanifnotsorted trivial
CanuseO(logn)binarysearchwhensorted
(
)
PS:mustrunanO(nlogn)sortingalgorithmonce
(
g )
g g
Binarysearchistrickytocode!
Instead,useC++STLalgorithm::lower_bound
I t d
C STL l ith l
b
d
CS3233 CompetitiveProgramming,
StevenHalim,SoC,NUS
4 Bitmask
4.
Bit
k
a.k.a.lightweightsetofBooleanorbitstring
Explanationvia:
http://www.comp.nus.edu.sg/~stevenha/visualization/bitmask.html
CS3233 CompetitiveProgramming,
StevenHalim,SoC,NUS
6 Stack,C++STLstack,JavaStack
6.
St k C STL t k J
St k
UsedbydefaultinRecursion,PostfixCalculation,
BracketMatching,etc
7. Queue,C
Queue, C++STLqueue,JavaQueue
STL queue, Java Queue
UsedinBreadthFirstSearch,TopologicalSort,etc
PS:Deque,usedinSlidingWindowalgorithm
PS D
d i Slidi Wi d l ith
CS3233 CompetitiveProgramming,
StevenHalim,SoC,NUS
NONLINEARDATASTRUCTURES
WITHBUILTINLIBRARIES
CS3233 CompetitiveProgramming,
StevenHalim,SoC,NUS
Fretnot,justuse:C++STLmap(JavaTreeMap)
UVa10226
UVa 10226 (HardwoodSpecies)
(Hardwood Species)*
CS3233 CompetitiveProgramming,
StevenHalim,SoC,NUS
InJava:TreeSet
Example:
p
UVa 11849 CD
CS3233 CompetitiveProgramming,
StevenHalim,SoC,NUS
Heap
Heap
C++STLalgorithm
g
hassomeheapalgorithms
p g
partial_sort usesheapsort
C++STLpriority_queue
C++ STL priority queue (JavaPriorityQueue)isheap
(Java PriorityQueue) is heap
PrimsandDijkstras algorithmsusepriorityqueue
But,werarelyseepureheapproblemsinICPC
B t
l
h
bl
i ICPC
CS3233 CompetitiveProgramming,
StevenHalim,SoC,NUS
Hash Table
HashTable
HashTable
AdvertisedO(1)forinsert,search,anddelete,but:
( )
,
,
,
Thehashfunctionmustbegood!
ThereisnoHashTableinC++STL(
There is no Hash Table in C++ STL ( inJavaAPI)
in Java API)
Nevertheless,O(logn)usingmap isusuallyok
DirectAddressingTable(DAT)
Di t Add
i T bl (DAT)
Ratherthanhashing,wemorefrequentlyuseDAT
UVa11340 (Newspaper)
CS3233 CompetitiveProgramming,
StevenHalim,SoC,NUS
SUPPLEMENTARY
CS3233 CompetitiveProgramming,
StevenHalim,SoC,NUS
#include <algorithm>
#include <cmath>
#include <cstdio>
cstdio
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#i l d <
#include
<vector>
t >
using namespace std;
Want More?
Add libraries that you frequently
use into this template, e.g.:
ctype.h
t
h
bitset
etc
CS3233 CompetitiveProgramming,
StevenHalim,SoC,NUS
typedef
typedef
typedef
typedef
long long
vector<int>
pair<int, int>
vector<ii>
ll;
vi;
ii;
vii;
3 SimplifyRepetitions/Loops!
3.
Si lif R titi /L
!
#define REP(i, a, b)
for (int i = int(a); i <= int(b); i++)
#define REPN(i, n)
REP (i, 1, int(n))
#define REPD(i, a, b)
for (int i = int(a); i >= int(b); i--)
#define TRvi(c, it) \
for (vi::iterator it = (c).begin(); it != (c).end(); it++)
#define TRvii(c,
TRvii(c it) \
for (vii::iterator it = (c).begin(); it != (c).end(); it++)
5. STL/Librariesalltheway!
/
y
isalpha (ctype.h)
inline bool isletter(char c) {
return (c>='A'&&c<='Z')||(c>='a'&&c<='z'); }
abs (math.h)
inline int abs(int a) { return a >= 0 ? a : -a; }
pow (math.h)
a int b) {
int power(int a,
int res=1; for (; b>=1; b--) res*=a; return res; }
UseSTLdatastructures:vector,stack,queue,priority_queue,map,set,etc
UseSTLalgorithms:sort,lower
g
,
_bound,max,min,max
,
,
,
_element,next
,
_p
permutation,etc
,
CS3233 CompetitiveProgramming,
StevenHalim,SoC,NUS
int main() {
// freopen(
freopen("input.txt",
input.txt , "r",
r , stdin); // don
don't
t retype test cases!
// freopen("output.txt", "w", stdout);
scanf and printf as per normal; // I prefer scanf/printf than
// cin/cout, C style is much easier
7. Usememset/assign/constructoreffectively!
CS3233 CompetitiveProgramming,
StevenHalim,SoC,NUS
Nowourcodingtasksaremuchsimpler
Typinglesscode=shortercodingtime
Typing less code = shorter coding time
=betterrankinprogrammingcontests
CS3233 CompetitiveProgramming,
StevenHalim,SoC,NUS
Quick Check
QuickCheck
1. Icancopewiththis
p
pace
2. Iamlostwithso
many new
manynew
informationinthe
pastfewslides
f
0
0 of 120
CS3233 CompetitiveProgramming,1
StevenHalim,SoC,NUS
0
2
5 Minutes Break
5MinutesBreak
Onedatastructureswithout builtinlibraries
willbediscussedinthelastpart
p
BinaryIndexed(Fenwick)Tree
Graph,UnionFindDisjointSets,andSegmentTree
Graph Union Find Disjoint Sets and Segment Tree
arenotdiscussedinthisyearsCS3233Week02
GraphDSiscoveredindetailsinCS2010/CS2020
G h DS i
d i d t il i CS2010/CS2020
UFDSiscoveredbrieflyinCS2010/CS2020
PleasestudySegmentTreeonyourown
Pl
t d S
tT
WetrynotsetanycontestprobleminvolvingSegmentTree
CS3233 CompetitiveProgramming,
StevenHalim,SoC,NUS
Time Check:
8.30pm
Graph (notdiscussedtoday,revisitedinWeek05/08)
U i Fi d Di j i t S t (notdiscussedtoday,readCh2onyourown)
UnionFindDisjointSets
( t di
dt d
d Ch2
)
SegmentTree (notdiscussedtoday,readCh2onyourown)
Fenwick Tree (discussedtoday)
FenwickTree
(discussed today)
DATASTRUCTURES
WITHOUTBUILTINLIBRARIES
CS3233 CompetitiveProgramming,
StevenHalim,SoC,NUS
Frequency
CumulativeFrequency
10
Binary
Range
CF
FT
0000
N/A
N/A
N/A
N/A
0001
0010
1..2
0011
0100
1..4
0101
0110
5..6
0111
1000
1..8
10
10
1001
10
Do you notice
any particular pattern?
Applythisformulaiterativelyuntilb is0
Analysis:
A
l i
This is
O(log n)
Why?
Example:ft_rsq(ft,
Example: ft rsq(ft, 6)
b=6=0110,b=b LSOne(b)=0110 0010,b'=4=0100
b'=4=0100,b=b LSOne(b)=0100 0100,b''=0,stop
Sum
Sumft[6]+ft[4]=5+2=7
ft[6] + ft[4] = 5 + 2 = 7
(seethebluearea
thatcoversrange
[1 4] + [5 6] = [1 6])
[1..4]+[5..6]=[1..6])
Example:ft_rsq(ft, 3, 6) =
ft_rsq(ft, 6) ft_rsq(ft, 3 1) =
ft_rsq(ft, 6) ft_rsq(ft, 2) =
k=5=0101,k'=k+LSOne(k)=0101 +0001,k'=6=0110
k'=6=0110,k''=k'+LSOne(k')=0110+0010,k''=8=1000
Andsoonwhilek<ft.size()
Observethatthedottedredline inthefigurebelowstabsthrough
therangesthatareundertheresponsibilityofindices5,6,and8
ft[5]
ft[5], 2updatedto4
2 updated to 4
ft[6], 5updatedto7
ft[8], 10updatedto12
// init: n+1
n 1 zeroes
// returns RSQ(1, b)
CS3233 CompetitiveProgramming,
StevenHalim,SoC,NUS
Ifyourcoderunsin0.342secs,whatisyourrank?
HowtouseFenwickTreetodealwiththisproblem?
p
CS3233 CompetitiveProgramming,
StevenHalim,SoC,NUS
Quick Check
QuickCheck
1. IamlostwithFenwickTree
2. Iunderstandthebasicsof
F
FenwickTree,butsincethis
i kT
b t i
thi
isnewforme,Imay/may
not be able to recognize
notbeabletorecognize
problemssolvablewithFT
3. IhavesolvedseveralFT
relatedproblemsbefore
0
0 of 120
CS3233 CompetitiveProgramming,
1
StevenHalim,SoC,NUS
0
2
0
3
Summary
TherearealotofgreatDataStructuresoutthere
Weneedthemostefficientoneforourproblem
DifferentDSsuitsdifferentproblem!
Manyofthemhavebuiltinlibraries
Forsomeothers,wehavetobuildourown(focusonFT)
Studytheselibraries!Donotrebuildthemduringcontests!
FromWeek03onwardsandfutureICPCs/IOIs,
useC++STLand/orJavaAPIandourbuiltinlibraries!
Now,yourteamshouldbeinrank3045(from60)
(stillsolving~12problemsoutof10,butfaster)
CS3233 CompetitiveProgramming,
StevenHalim,SoC,NUS