小Ho很喜欢在课间去小卖部买零食。然而不幸的是,这个学期他又有在一教的课,而一教的小卖部姐姐以冷若冰霜著称。第一次去一教小卖部买零食的时候,小Ho由于不懂事买了好一大堆东西,被小卖部姐姐给了一个“冷若冰霜”的眼神,食欲都下降了很多。
从那以后,小Ho就学乖了,去小卖部买东西只敢同时买3包以内的零食,并且价格加起来必须是5的整数倍,方便小卖部姐姐算价格。
但是小Ho不擅长计算,所以他把小卖部里所有零食的价格以及他对这个零食的渴望度都告诉了你,希望你能够帮他计算出在不惹恼小卖部姐姐的前提下,能够买到零食的渴望度之和最高是多少?
输入
每个输入文件包含多组测试数据,在每个输入文件的第一行为一个整数Q,表示测试数据的组数。
每组测试数据的第一行为一个正整数N,表示小卖部中零食的数量。
接下来的N行,每行为一个正实数A和一个正整数B,表示这种零食的价格和小Ho对其的渴望度。
一种零食仅有一包。
对于100%的数据,满足1 <= Q <= 10,1<=N<=50,0<A<=10,1<=B<=100。
对于100%的数据,满足A的小数部分仅可能为0.5或0。
输出
对于每组测试数据,输出一个整数Ans,表示小Ho可以获得最大的渴望度之和。
样例输入
1
4
0.5 6
4.5 7
5.0 4
2.0 9
样例输出
17
#include <iostream>
using namespace std;
int cost[50];
int sat[50];
int getMax(int n) {
int res = 0;
for (int i=0; i<n; i++)
if (cost[i] % 50 == 0)
res = max(res, sat[i]);
for (int i=0; i<n; i++)
for (int j=i+1; j<n; j++)
if ((cost[i]+cost[j])%50==0)
res = max(res, sat[i]+sat[j]);
for (int i=0; i<n; i++)
for (int j=i+1; j<n; j++)
for (int k=j+1; k<n; k++)
if ((cost[i]+cost[j]+cost[k])%50==0)
res = max(res, sat[i]+sat[j]+sat[k]);
return res;
}
int main() {
int n, m;
cin >> n;
double temp;
while (n--) {
cin >> m;
for (int i=0; i<m; i++) {
scanf("%lf %d", &temp, &sat[i]);
cost[i] = 10*temp;
}
cout << getMax(m) << endl;
}
return 0;
}
小Hi和小Ho是一对好朋友,出生在信息化社会的他们对编程产生了莫大的兴趣,他们约定好互相帮助,在编程的学习道路上一同前进。
这一天,他们遇到了一本词典,于是小Hi就向小Ho提出了那个经典的问题:“小Ho,你能不能对于每一个我给出的字符串,都在这个词典里面找到以这个字符串开头的所有单词呢?”
身经百战的小Ho答道:“怎么会不能呢!你每给我一个字符串,我就依次遍历词典里的所有单词,检查你给我的字符串是不是这个单词的前缀不就是了?”
小Hi笑道:“你啊,还是太年轻了!~假设这本词典里有10万个单词,我询问你一万次,你得要算到哪年哪月去?”
小Ho低头算了一算,看着那一堆堆的0,顿时感觉自己这辈子都要花在上面了…
小Hi看着小Ho的囧样,也是继续笑道:“让我来提高一下你的知识水平吧~你知道树这样一种数据结构么?”
小Ho想了想,说道:“知道~它是一种基础的数据结构,就像这里说的一样!”
小Hi满意的点了点头,说道:“那你知道我怎么样用一棵树来表示整个词典么?”
小Ho摇摇头表示自己不清楚。
提示一:Trie树的建立
“你看,我们现在得到了这样一棵树,那么你看,如果我给你一个字符串ap,你要怎么找到所有以ap开头的单词呢?”小Hi又开始考校小Ho。
“唔…一个个遍历所有的单词?”小Ho还是不忘自己最开始提出来的算法。
“笨!这棵树难道就白构建了!”小Hi教训完小Ho,继续道:“看好了!”
提示二:如何使用Trie树
提示三:在建立Trie树时同时进行统计!
“那么现在!赶紧去用代码实现吧!”小Hi如是说道
输入
输入的第一行为一个正整数n,表示词典的大小,其后n行,每一行一个单词(不保证是英文单词,也有可能是火星文单词哦),单词由不超过10个的小写英文字母组成,可能存在相同的单词,此时应将其视作不同的单词。接下来的一行为一个正整数m,表示小Hi询问的次数,其后m行,每一行一个字符串,该字符串由不超过10个的小写英文字母组成,表示小Hi的一个询问。
在20%的数据中n, m<=10,词典的字母表大小<=2.
在60%的数据中n, m<=1000,词典的字母表大小<=5.
在100%的数据中n, m<=100000,词典的字母表大小<=26.
本题按通过的数据量排名哦~
输出 对于小Hi的每一个询问,输出一个整数Ans,表示词典中以小Hi给出的字符串为前缀的单词的个数。
样例输入
5
babaab
babbbaaaa
abba
aaaaabaa
babaababb
5
babb
baabaaa
bab
bb
bbabbaab
样例输出
1
0
3
0
0
#include <iostream>
#include <cstring>
using namespace std;
#define MAX 105
struct tree {
char val;
int cnt;
tree *next[26];
tree() {
cnt = 0;
for (int i=0; i<26; i++)
next[i] = NULL;
}
};
tree root;
void insertWord(char *str) {
tree* head = &root;
for (int i=0; i<strlen(str); i++) {
int index = str[i]-'a';
if (head->next[index]==NULL) {
tree *node = new tree;
node->val = str[i];
head->next[index] = node;
}
head = head->next[index];
head->cnt++;
}
}
int getMax(char *str) {
tree *head = &root;
for (int i=0; i<strlen(str); i++) {
int index = str[i]-'a';
if (head->next[index]==NULL) return 0;
else
head = head->next[index];
}
return head->cnt;
}
int main() {
int n, m;
cin >> n;
char str[MAX];
for (int i=0; i<n; i++) {
cin >> str;
insertWord(str);
}
cin >> m;
while (m--) {
cin >> str;
cout << getMax(str) << endl;
}
return 0;
}
Git and Github Tutorial
Open a Github Account from Github.
Install git in Linux
$ sudo yum install git
When you install Git is to set user name and email address.
$ git config —global user.name “John”
$ git config -global user.email john@example.com
$ git config -—list
$ git config user.name
Get Github help
$ git help config
Initializing a repository in an existing directory
$ git init
$ git init Algorithm
Start version-controlling existing files
Get a copy of an existing Git repository
$ git clone https://github.com/libgit2/libgit2
Check git status
$ git status
Trace files
$ git add README.md
$ git add *
$ git add *.c
$ git status
$ git status -s
You’ll have a class of files that you don’t want Git to automatically add or even show you as being untracked. And u can get github ignore list : https://github.com/github/gitignore
$ cat .gitignore
See what you’ve changed but not yet staged
$ git diff
$ git diff —cached
Commit changes and push
$ git commit -m “first commit”
$ git commit -a //jump git add
$ git push
$ git push --set-upstream origin master
$ git push -u origin master
Remove files
$ rm README.md
$ git rm README.md
$ git rm log/\*.log
Change file name
$ git mv file_from to file_to
$ git mv
Check history
$ git log
Shows the difference introduced in each commit
$ git log -p -2
$ git log —-stat
Shows you where the branch pointers are pointing
$ git log --decorate
Display an ASCII graph of the branch and merge history beside the log output.
$ git log —-graph
$ git log --decorate --graph
Undo things
$ git commit -m “first commit”
$ git add forgotten_file
$ git commit —-amend
Upstaging a staged file
$ git add *
Then u want to to unstage README.md file
$ git reset README.md
$ git checkout —- README.md
Remote
$ git remote
$ git remote show origin
$ git remote iv
$ git remote add origin https://github.com/Shanshan-IC/Algorithm.git
$ git remote rename pb paul
$ git remote rm paul
Fetch all the information that Paul has but that you don’t yet have in your repository,
$ git fetch pb
Get data from remote projects
$ git fetch origin
Tag
$ git tag
$ git tag v.1.0
$ git show v.1.0
Share tag
$ git push origin v.1.0
$ git checkout -b new branch v.1.0
Branch
Get new branch
$ git branch testing
Switch branch
$ git checkout testing
Get a new branch and switch to it
$ git checkout -b testing2
Merge branch
$ get checkout master
$ get merge testing2
After merge, delete branch
$ git branch -d testing2
But if there are conflicts between merge, have to solve it manually
$ git mergetool
$ git commit
Check branch things
$ git branch -v
$ git branch —-merge
If you want to learn something more, please visit the website: https://git-scm.com/book/en/v2
struct Interval {
int start;
int end;
Interval() : start(0), end(0) {}
Interval(int s, int e) : start(s), end(e) {}
};
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
class Solution {
public:
vector<Interval> merge(vector<Interval>& intervals) {
vector<Interval> res;
if (intervals.empty()) return res;
sort(intervals.begin(), intervals.end(), [](Interval &i, Interval &j){return i.start<j.start;});
const int n = intervals.size();
for (int i=0; i<n; i++) {
if (i+1<n && intervals[i+1].start<=intervals[i].end) {
intervals[i+1].end = max(intervals[i].end, intervals[i+1].end);
intervals[i+1].start = min(intervals[i].start, intervals[i+1].start);
}
else
res.push_back(intervals[i]);
}
return res;
}
};
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
Push back to the vector and then use the previous merge function.
class Solution {
public:
vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
vector<Interval> res;
intervals.push_back(newInterval);
sort(intervals.begin(), intervals.end(), [](Interval &i, Interval &j){return i.start<j.start;});
const int n = intervals.size();
for (int i=0; i<n; i++) {
if (i+1<n && intervals[i+1].start<=intervals[i].end) {
intervals[i+1].end = max(intervals[i].end, intervals[i+1].end);
intervals[i+1].start = min(intervals[i].start, intervals[i+1].start);
}
else
res.push_back(intervals[i]);
}
return res;
}
};
Stack and Heap Basic Knowledge (some from geeksforgeeks)
1) Heap Sort: Heap Sort uses Binary Heap to sort an array in O(nLogn) time.
2) Priority Queue: Priority queues can be efficiently implemented using Binary Heap because it supports insert(), delete() and extractmax(), decreaseKey() operations in O(logn) time. Binomoial Heap and Fibonacci Heap are variations of Binary Heap. These variations perform union also efficiently.
3) Graph Algorithms: The priority queues are especially used in Graph Algorithms
A typical Priority Queue requires following operations to be efficient.
Get Top Priority Element (Get minimum or maximum)
Insert an element
Remove top priority element
Decrease Key
Since Binary Heap is implemented using arrays, there is always better locality of reference and operations are more cache friendly.
Although operations are of same time complexity, constants in Binary Search Tree are higher.
We can build a Binary Heap in O(n) time. Self Balancing BSTs require O(nLogn) time to construct.
Binary Heap doesn’t require extra space for pointers.
Binary Heap is easier to implement.
There are variations of Binary Heap like Fibonacci Heap that can support insert and decrease-key in Θ(1) time
Stack is a linear data structure which follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out).
Mainly the following three basic operations are performed in the stack: Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition.
Pop: Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be an Underflow condition.
Peek: Get the topmost item.
There are many real life examples of stack. Consider the simple example of plates stacked over one another in canteen. The plate which is at the top is the first one to be removed, i.e. the plate which has been placed at the bottommost position remains in the stack for the longest period of time. So, it can be simply seen to follow LIFO/FILO order.
Implementation: http://geeksquiz.com/stack-set-1/
There are two ways to implement a stack:
Using array
Using linked list
Balancing of symbols:
Infix to Postfix/Prefix conversion
Redo-undo features at many places like editors, photoshop.
Forward and backward feature in web browsers
Used in many algorithms like Tower of Hanoi, tree traversals, stock span problem, histogram problem.
Other applications can be Backtracking, Knight tour problem, rat in a maze, N queen problem and sudoku solver
String and Array
// define array in the stack
int array[arraySize];
// define array in the heap
int *array = new int[arraySize];
// free the memory after using it
delete[] array;
Array can be accessed by index, so modify and read an element, O(1). Delete and Insert elements needs to move the later elements, O(N).
Some string functions used frequently
string str ("This is a string");
int length = str.length(); // length equals to 16
str.erase(0,10); // str becomes "string", with length 6 after erasure
string subStr = str.substr(10,6); // subStr equals to "string", with length 6
Brute-Force算法: 顺序遍历母串,将每个字符作为匹配的起始字符,判断是否匹配子串。时间复杂度 O(mn)。
Rabin-Karp算法:将每一个匹配子串映射为一个哈希值。例如,将子串看做一个多进制数,比较它的值与母串中相同长度子串的哈希值,如果相同,再细致地按字符确认字符串是否确实相同。顺序计算母串哈希值的过程中,使用增量计算的方法:扣除最高位的哈希值,增加最低位的哈希值。因此能在平均情况下做到O(m+n)。