ACM notes Why… ? Not always an easy question! Entropy problem -- Huffman Codes InputOutput A..AB..BC..CD..DE..EF784 224 3.5 compression ratio, to 1 place.

Slides:



Advertisements
Similar presentations
A C++ Crash Course Part II UW Association for Computing Machinery Questions & Feedback.
Advertisements

Hold data and provide access to it. Random-access containers: -Allow accessing any element by index -arrays, vectors Sequential containers: -Allow accessing.
MSU/CSE 260 Fall Integer Representations & Base Conversion Section 3.6.
CSE202: Lecture 2The Ohio State University1 Variables and C++ Data Types.
1 Hash Tables Gordon College CS Hash Tables Recall order of magnitude of searches –Linear search O(n) –Binary search O(log 2 n) –Balanced binary.
Primitive Variable types Basic types –char (single character or ASCII integer value) –int (integer) –short (not longer than int) –long (longer than int)
Differences between Java and C CS-2303, C-Term Differences between Java and C CS-2303, System Programming Concepts (Slides include materials from.
CPSC 411, Fall 2008: Set 4 1 CPSC 411 Design and Analysis of Algorithms Set 4: Greedy Algorithms Prof. Jennifer Welch Fall 2008.
Chapter 9: Greedy Algorithms The Design and Analysis of Algorithms.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2: Introduction to C++ Starting Out with C++ Early Objects Sixth.
Chapter 9 Greedy Technique Copyright © 2007 Pearson Addison-Wesley. All rights reserved.
More on Numerical Computation CS-2301 B-term More on Numerical Computation CS-2301, System Programming for Non-majors (Slides include materials from.
Hash Tables1 Part E Hash Tables  
Chapter 9 Formatted Input/Output Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
 2007 Pearson Education, Inc. All rights reserved C Formatted Input/Output.
CPSC 411, Fall 2008: Set 4 1 CPSC 411 Design and Analysis of Algorithms Set 4: Greedy Algorithms Prof. Jennifer Welch Fall 2008.
C Formatted Input/Output /* Using Integer Conversion Specifiers */ #include int main ( ) { printf( "%d\n", 455 ); printf( "%i\n", 455 ); printf( "%d\n",
 2007 Pearson Education, Inc. All rights reserved C Formatted Input/Output.
Lecture 11 Standard Template Library Stacks, Queue, and Deque Lists Iterators Sets Maps.
Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Elements of a C++ program 1. Review Algorithms describe how to solve a problem Structured English (pseudo-code) Programs form that can be translated into.
Dr. Yingwu Zhu STL Vector and Iterators. STL (Standard Template Library) 6:14:43 AM 2 A library of class and function templates Components: 1. Containers:
DATA STRUCTURES ACM EXECUTIVE BODY 2k11.  A series of elements of same type  Placed in contiguous memory locations  Can be individually referenced.
Data Structures Using C++ 2E
CS1 Lesson 2 Introduction to C++ CS1 Lesson 2 -- John Cole1.
ACM notes Can work on the problems anytime throughout the term Contest conflict -- The GRE subject test is Nov. 10th! int x; while (cin >> x) { cout
Sales person receive RM200/week plus 9% of their gross sales for that week. Write an algorithms to calculate the sales person’s earning from the input.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.
Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp.
CH2 – Using Data. Constant Something which cannot be changed Data Type Format and size of a data item Intrinsic Data Types Pg. 47 – Table 2-1 Basic ones.
The Fundamentals of C++ Chapter 2: Basic programming elements and concepts JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
CSE1222: Lecture 2The Ohio State University1. mathExample2.cpp // math example #include using namespace std; int main() { cout
Chapter 2 Simple Data Types By C. Shing ITEC Dept Radford University.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 9 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
Another dynamic program %...*..*..*% % % %*..*******% %*.*.***.*.% Q: What is the shortest path that delivers papers.
CS342 Data Structures End-of-semester Review S2002.
A chance to “improve” your C/C++ … Preparation for the ACM competition... Problem Insight and Execution... Get into the minds of the judges Anxiety! 1.
Chapter 3 – Variables and Arithmetic Operations. Variable Rules u Must declare all variable names –List name and type u Keep length to 31 characters –Older.
CSCE350 Algorithms and Data Structure Lecture 19 Jianjun Hu Department of Computer Science and Engineering University of South Carolina
Basic I/O in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Stream Model of I/O header file: A stream provides a connection.
5-1 Embedded Systems C Programming Language Review and Dissection III Lecture 5.
1 Homework –Continue Reading K&R Chapter 2 –We’ll go over HW2 at end of class today –Continue working on HW3 Questions?
1 Greedy Technique Constructs a solution to an optimization problem piece by piece through a sequence of choices that are: b feasible b locally optimal.
CS4710 Algorithms. What is an Algorithm? An algorithm is a procedure to perform some task. 1.General - applicable in a variety of situations 2.Step-by-step.
Introduction to Computer Organization & Systems Topics: Types in C: floating point COMP C Part III.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Input and Output.
Characters and Strings
Greedy Algorithms Analysis of Algorithms.
ACM notes Sometimes a problem is much more difficult than expected! Basic approach:
C is a high level language (HLL)
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
DATA PROCESSING Gary Sham 15/1/2011. Data Processing  Data Processing ≠ Algorithm  Data Processing:  Get the input so that we can use it in our program.
Analysis of Algorithms CS 477/677 Instructor: Monica Nicolescu Lecture 18.
CMSC 202 Lesson 26 Miscellaneous Topics. Warmup Decide which of the following are legal statements: int a = 7; const int b = 6; int * const p1 = & a;
C Formatted Input/Output
CSE 220 – C Programming Bitwise Operators.
Greedy Technique.
TMF1414 Introduction to Programming
Basic Data Structures.
Basic Data Structures.
Lecture 13 Input/Output Files.
Bits and Bytes Topics Representing information as bits
Bits and Bytes Topics Representing information as bits
Differences between Java and C
Binary multiplication
An Introduction to STL.
Presentation transcript:

ACM notes Why… ? Not always an easy question! Entropy problem -- Huffman Codes InputOutput A..AB..BC..CD..DE..EF compression ratio, to 1 place of precision bits used in ASCII bits used in an optimal “prefix-free” encoding chars 1

Prefix-free Codes via binary trees A..AB..BC..CD..DE..EF D CD ABCDEF BCDF BF A E C 16 AE B F *2 + 49*3 = 245

Prefix-free Codes via binary trees A..AB..BC..CD..DE..EF D CD ABCDEF BCDF BF A E C 16 AE B F *2 + 49*3 = codewords are read down the paths

Huffman Codes Building the tree from the bottom up… A..AB..BC..CD..DE..EF EF 10 E F A..AB..BC..CD..DE..F

Huffman Codes Building the tree from the bottom up… A..AB..BC..CD..DE..F EF 10 E F 9 1 D DEF 22 A..AD..E..FB..BC..C

Huffman Codes Building the tree from the bottom up… EF 10 E F 9 1 DEFBC B C D A..AB..CD..E..F A..AD..E..FB..BC..C

Huffman Codes Building the tree from the bottom up… EF 10 E F 9 1 DEF BCDEF BC B C D 12 A A..AB..CD..E..F A..AB..C..D..E..F 4058

Huffman Codes Building the tree from the bottom up… EF 10 E F 9 1 DEF ABCDEF BCDEF BC B C D 12 A A..AB..C..D..E..F 4058 A..B..C..D..E..F 58

Huffman Codes Total number of bits needed... EF 10 E F 9 1 DEF ABCDEF BCDEF BC B C D 12 A *1 + 36*3 + 12*3 + 10*4 = 224

Graphs A B E D C Adjacency List Representation [A,E], [A,B], [A,C], [B,D], [B,E], [C,B], [D,A], [D,C], [E,D] (vector or array of pairs)

Graphs A B E D C A B C D E FROM TO Matrix representation ABCDE [A,E], [A,B], [A,C], [B,D], [B,E], [C,B], [D,A], [D,C], [E,D] (2d array) Adjacency List Representation (vector or array of pairs ?)

Problems Roman Forts ( forts.cc ) J I C G A F D B E K H fortify the most vulnerable...

Problems Single Points of Failure ( spf.cc ) Network #1 SPF node 3 leaves 2 subnets Input 1 Output 1 Graph 1 Network #2 No SPF nodes Output 2 Graph 2

All-pairs shortest paths A B C D E D 0 = (d ij ) A B C D E D 1 = (d ij ) 1 d ij = shortest distance from i to j through {1, …, k} k d ij = k A B C D E “Floyd-Warshall algorithm”

All-pairs shortest paths A B C D E D 0 = (d ij ) A B C D E D 1 = (d ij ) 1 d ij = shortest distance from i to j through {1, …, k} k d ij = k A B C D E “Floyd-Warshall algorithm”

Geometric Problems A B E D C Adjacency List Representation [A,E], [A,B], [A,C], [B,D], [B,E], [C,B], [D,A], [D,C], [E,D] (vector or array of pairs) code resources to keep in mind

All-pairs shortest paths A B C D E D 2 = (d ij ) A B C D E D 3 = (d ij ) A B C D E D 4 = (d ij ) 4 A B C D E D 5 = (d ij ) 5 to store the path, another matrix can track the last intermediate vertex

Graphs Representations InputOutput AAAAABCD compression ratio, to 1 place of precision bits used in ASCII bits used in an optimal “prefix-free” encoding

Graphs Representations InputOutput AAAAABCD compression ratio, to 1 place of precision bits used in ASCII bits used in an optimal “prefix-free” encoding

Problems Entropy InputOutput AAAAABCD compression ratio, to 1 place of precision bits used in ASCII bits used in an optimal “prefix-free” encoding A 0 B 10 C 110 D 111

Problems N-Credible Mazes InputOutput Maze #1 can be travelled startend dimensions edge start edge end (or not…)

C++ STL set s; // basically a bin. tree s.size(); // returns an int s.insert(14); // adds 14 s.insert(-9); // adds -9 s.insert(42); // adds 42 set ::iterator i; // may want to typedef // think of an iterator as a pointer i = s.find(42); // return 42’s iterator cout << (*i) << endl; // prints 42 cout << (*--i)); // prints... i = s.find(43); // not there ! // at this point ( i == s.end() ) is true s.erase(-9); // removing elements multiset m; // holds multiple copies multiset #include set #include

Breadth-first search algorithm data structures queue, deque, hashtable (map)

C++ STL vector v; // basically an int array v.reserve(10); // assure 10 spots v.push_back(42); // adds 42 to the end v.back(); // returns 42 v.pop_back(); // removes 42 v.size(); // # of elements v[i]; // ith element sort( v.begin(), v.end() ); // default sort sort( v.begin(), v.end(), mycompare ); deque d; // double-ended queue d.push_front(42); // add to front d.front(42); // return front element d.pop_front(42); // remove from front sort #include vector #include deque #include last time

Other problems Change counting input: output: There are 292 ways to make $1.00 There are 2 ways to make $0.06 Sigma series input: output: Shortest sequences from 1 to N such that each element is the sum of two previous elements.

Useful C functions int atoi(char* s); double atof(char* s); int strcasecomp(char* s1, char* s2); long strtol(char* s, NULL, int base) strtol(“Charlie”, NULL, 36) == L converts C strings to ints atoi(“100”) == 100 converts C strings to doubles atoi(“100.0”) == case-insensitive C string comparison strcasecmp(“aCm”,“ACm”) == 0 arbitrary conversion from a string in bases (2-36) to a long int use man for more...

sprintf int sprintf(char* str, char* format,...); prints anything to the string str char str[100]; sprintf(str,“%d”,42); // str is “42” sprintf(str,“%f”,42.0); // str is “42.0” sprintf(str,“%10d”,42); // str is “ 42” sprintf(str,“%-10d”,42); // str is “42 ” flexible formatting: right/left justify:

A chance to “improve” your C/C++ … Preparation for the ACM competition... Problem Insight and Execution... Get into the minds of the judges Anxiety! 1 2 Two ACM programming skills

Get into the minds of the judges Key Skill #1: mindreading “What cases should I handle?” spectrum 100% 0%

Key Skill #2: anxiety Anxiety!

Dynamic Programming Strategy: create a table of partial results & build on it. divis.cc T(n) = T(3n+1) + 1 if n odd T(n) = number of steps yet to go T(n) = T(n/2) + 1 if n even

Dynamic Programming Keys: create a table of partial results, articulate what each table cell means, then build it up... divis.cc T[i][j] is 1 if i is a possible remainder using the first j items in the list. Table T 3 j = items considered so far i = possible remainder the list the divisor 4

Dynamic programs can be short #include vector v(10000); vector m(100); // old mods vector m2(100); // new mods int n, k; bool divisible() { fill(m.begin(),m.end(),false); m[0] = true; for (int i=0; i<n; i++) { /* not giving away all of the code */ /* here the table is built (6 lines) */ } return m[0]; } int main() { cin >> n; // garbage while (cin >> n) { cin >> k; for (int i=0; i<n; i++) { cin >> v[i]; v[i] = abs(v[i]); v[i] %= k; } cout << (divisible() ? "D" : "Not d") << "ivisible\n"; } cout << endl; } acknowledgment: Matt Brubeck STL:

General ACM Programming Try brute force first (or at least consider it) -- sometimes it will work fine… -- sometimes it will take a _bit_ too long -- sometimes it will take _way_ too long for (int j=1 ; j<N ; ++j) { cin >> Array[i]; } Table[i + n % k] = 1; Table[i - n % k] = 1; filling in the table in the “divis” problem:getting the input in the “pea” problem: Best bugs from last week:

New Problem Input A list of words Word Chains Output yes or no -- can these words be chained together such that the last letter of one is the first letter of the next… ? doze aplomb ceded dozen envy ballistic yearn hertz jazz hajj zeroth

Knapsack Problem V(n,w) = max value stealable w/ ‘n’ objects & ‘w’ weight V(n,w) = object wt. val Maximize loot w/ weight limit of 4. 4 Number of objects considered Weight available for use n w

C Output printf, fprintf, sprintf(char* s, const char* format, …) the destinationthe format string the values h.412-#0%d start character flags - left-justify 0 pad w/ zeros + use sign (+ or -) (space) use sign ( or -) # deviant operation minimum field width precision size modifier h short l long (lowercase L) L long double type d decimal integers u unsigned (decimal) ints o octal integers x hexadecimal integers f doubles (floats are cast) e doubles (exp. notation) g f or e, if exp < -3 or -4 c character s string n outputs # of chars written !! % two of these print a ‘%’ allowed size modifiers possible format strings

C Output %10.4d value = 42value = %-#12x 0x2a0xffffffd6 %+10.4g value = 42value = %- 10.4g %-#10.4g value = “forty-two” %10.5s forty

const int p=1,n=5,d=10,q=25,h=50; int counter=0; int pn, nn, dn, qn, hn; for (hn = 0; hn*h <= num; hn++) for (qn = 0; hn*h + qn*q <= num; qn++) for (dn = 0; hn*h + qn*q + dn*d <= num; dn++) for (nn = 0; hn*h + qn*q + dn*d + nn*n <= num; nn++) for (pn = 0; hn*h + qn*q + dn*d + nn*n + pn*p <= num; pn++) { if (hn*h + qn*q + dn*d + nn*n + pn*p == num) counter++; } Change Brute Force Dynamic Programming 1¢ 1¢, 5¢ 1¢, 5¢, 10¢ 1 using total 1¢ 2¢3¢ 4¢ 5¢ 6¢7¢ 8¢ 9¢ 10¢11¢ 12¢ ¢