mirror of
https://github.com/heqin-zhu/algorithm.git
synced 2024-03-22 13:30:46 +08:00
Update readme
This commit is contained in:
parent
3ac8e543cf
commit
a8fcf412ca
1
.gitignore
vendored
1
.gitignore
vendored
|
@ -4,3 +4,4 @@
|
|||
tree_link.py
|
||||
__pycache__/**
|
||||
!.gitignore
|
||||
todo
|
||||
|
|
32
README.md
32
README.md
|
@ -1,4 +1,4 @@
|
|||
# Algorithm and data structures
|
||||
# Algorithm and Data Structures
|
||||
>Notes and codes for learning algorithm and data structures :smiley:
|
||||
|
||||
Some pictures and idead are from `<<Introduction to Algotithm>>
|
||||
|
@ -11,40 +11,36 @@ Some scripts may have bugs or not be finished yet.
|
|||
|
||||
# Notice
|
||||
Currently, Github can't render latex math formulas.
|
||||
So,if you wannt to view the notes which contains latex math formulas and are in markdown format, you can visit [my blog](https://mbinary.coding.me)
|
||||
So,if you wannt to view the notes which contain latex math formulas and are in markdown format, you can visit [my blog](https://mbinary.coding.me)
|
||||
|
||||
# index
|
||||
# Index
|
||||
* [.](.)
|
||||
* [notes](./notes)
|
||||
* [alg-general.md](./notes/alg-general.md)
|
||||
* [hashTable.md](./notes/hashTable.md)
|
||||
* [README.md](./notes/README.md)
|
||||
* [red-black-tree.md](./notes/red-black-tree.md)
|
||||
* [sort.md](./notes/sort.md)
|
||||
* [tree.md](./notes/tree.md)
|
||||
* [red-black-tree.md](./notes/red-black-tree.md)
|
||||
* [algorithm](./algorithm)
|
||||
* [8Astar.py](./algorithm/8Astar.py)
|
||||
* [cantor.cc](./algorithm/cantor.cc)
|
||||
* [EIGHT.py](./algorithm/EIGHT.py)
|
||||
* [manacher.py](./algorithm/manacher.py)
|
||||
* [markov.py](./algorithm/markov.py)
|
||||
* [README.md](./algorithm/README.md)
|
||||
* [sort](./algorithm/sort)
|
||||
* [sunday.py](./algorithm/sunday.py)
|
||||
* [dataStructure](./dataStructure)
|
||||
* [allOone](./dataStructure/allOone)
|
||||
* [redblack tree.py](./dataStructure/redBlackTree.py)
|
||||
* [binaryHeap.py](./dataStructure/binaryHeap.py)
|
||||
* [binaryIndexedTree.cc](./dataStructure/binaryIndexedTree.cc)
|
||||
* [binaryTree.py](./dataStructure/binaryTree.py)
|
||||
* [redBlackTree.py](./dataStructure/redBlackTree.py)
|
||||
* [hashTable.py](./dataStructure/hashTable.py)
|
||||
* [huffman.cc](./dataStructure/huffman.cc)
|
||||
* [splayTree.py](./dataStructure/splayTree.py)
|
||||
* [allOone](./dataStructure/allOone)
|
||||
* [binaryHeap.py](./dataStructure/binaryHeap.py)
|
||||
* [binaryTree.py](./dataStructure/binaryTree.py)
|
||||
* [graph](./dataStructure/graph)
|
||||
* [huffman](./dataStructure/huffman)
|
||||
* [leftHeap.py](./dataStructure/leftHeap.py)
|
||||
* [loserTree.py](./dataStructure/loserTree.py)
|
||||
* [map](./dataStructure/map)
|
||||
* [README.md](./dataStructure/README.md)
|
||||
* [segTree.cc](./dataStructure/segTree.cc)
|
||||
* [splayTree.py](./dataStructure/splayTree.py)
|
||||
* [stack](./dataStructure/stack)
|
||||
* [map.cc](./dataStructure/map.cc)
|
||||
* [polynomial.cpp](./dataStructure/polynomial.cpp)
|
||||
* [polynomial.py](./dataStructure/polynomial.py)
|
||||
* [trie.py](./dataStructure/trie.py)
|
||||
* [winnerTree.py](./dataStructure/winnerTree.py)
|
||||
|
|
|
@ -102,11 +102,52 @@ def getPath(s,index):
|
|||
if ct is 0:
|
||||
return cur.path
|
||||
cur.move()
|
||||
def info():
|
||||
print('input a 3x3 matrix in one line')
|
||||
print('from left to right,from up to down')
|
||||
print('such as 56831247x represent matrix as follow')
|
||||
print('5 6 8\n3 1 2\n4 7 x')
|
||||
print('then, if it has, I will print the path of moving x to reach state as follows')
|
||||
print('1 2 3\n4 5 6\n7 8 x')
|
||||
print('print q to quit')
|
||||
|
||||
from random import shuffle
|
||||
case = list('12345678x')
|
||||
def genCase():
|
||||
tmp = case.copy()
|
||||
shuffle(tmp)
|
||||
print(f'Using random data: {tmp}')
|
||||
index = -1
|
||||
for i,j in enumerate(tmp):
|
||||
if j=='x':
|
||||
index = i
|
||||
break
|
||||
tmp[index] = '9'
|
||||
return tmp,index
|
||||
def isValid(li):
|
||||
for i in '123456789':
|
||||
if not i in li:
|
||||
print('Invalid Input')
|
||||
return False
|
||||
return True
|
||||
|
||||
def run():
|
||||
while 1:
|
||||
print('\n\n'+'-'*10+'Game Begins'+ '-'*10)
|
||||
info()
|
||||
s=input('input: ')
|
||||
if s=='q' or s=='Q' or s=='quit':
|
||||
break
|
||||
index = s.find('x')
|
||||
li = list(s)
|
||||
if index != -1:
|
||||
li[index] = '9'
|
||||
if not isValid(li):
|
||||
li, index = genCase()
|
||||
if solvable(li):
|
||||
print(''.join(getPath(li,index)))
|
||||
else:print('unsolvable')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
s=input()
|
||||
index = s.find('x')
|
||||
s =list(s)
|
||||
s[index] = '9'
|
||||
if solvable(s):print(''.join(getPath(s,index)))
|
||||
else:print('unsolvable')
|
||||
run()
|
||||
|
|
|
@ -1,73 +0,0 @@
|
|||
''' mbinary
|
||||
#########################################################################
|
||||
# File : EIGHT.py
|
||||
# Author: mbinary
|
||||
# Mail: zhuheqin1@gmail.com
|
||||
# Blog: https://mbinary.coding.me
|
||||
# Github: https://github.com/mbinary
|
||||
# Created Time: 2018-05-19 23:06
|
||||
# Description:
|
||||
#########################################################################
|
||||
'''
|
||||
|
||||
from colectons import deque
|
||||
isVisted = [0]*362880
|
||||
fac = [1,2,6,24,120,720,5040,40320]
|
||||
lf = len(fac)
|
||||
x= '9'
|
||||
def cantor(s):
|
||||
sum = 0
|
||||
ls = len(s)
|
||||
for i in range(ls):
|
||||
count = 0
|
||||
for j in range(i+1;ls):
|
||||
if s[i] > s[j]: count +=1
|
||||
sum += count*fac[lf-i-1]
|
||||
return sum
|
||||
|
||||
que = deque()
|
||||
class state:
|
||||
def __init__(self,s,p,step=0,last=0):
|
||||
self.x = p
|
||||
self.s = list(s)
|
||||
self.step = step
|
||||
self.path = []
|
||||
self.last = last
|
||||
def move(self):
|
||||
dir = [-3:'u',1:'r',3:'d',-1:'l']
|
||||
if self.last in dir :
|
||||
del dir[-self.last]
|
||||
if self.x<3:
|
||||
del dir[-3]
|
||||
if self.x>5:
|
||||
del dir[3]
|
||||
if self.x%3 is 0:
|
||||
del dir[-1]
|
||||
if self.x%3 is 2:
|
||||
del dir[1]
|
||||
for i in dir.keys():
|
||||
s = list(self.s)
|
||||
tmp = self.x + i
|
||||
s[self.x] = s[tmp]
|
||||
s[tmp] = x
|
||||
if not isVisted[cantor(s)]:
|
||||
new = state(s,tmp,self.step +1,i)
|
||||
new.path = self.path + [dir[i]]
|
||||
que.append(new)
|
||||
|
||||
def getPath(s):
|
||||
index = s.find('x')
|
||||
s =list(s)
|
||||
s[index] = '9'
|
||||
que.append(state(s,index,0,0))
|
||||
while que != deque():
|
||||
cur = que.popleft()
|
||||
ct = cantor(cur.s)
|
||||
if ct is 362879:
|
||||
return cur.path
|
||||
isVisted[] = 1
|
||||
cur.move()
|
||||
|
||||
if __name__ == '__main__':
|
||||
s=input()
|
||||
print(''.join(getPath(s)))
|
|
@ -1,18 +0,0 @@
|
|||
# 算法实现
|
||||
# 索引
|
||||
|
||||
* [.](.)
|
||||
* [8Astar.py](./8Astar.py)
|
||||
* [cantor.cc](./cantor.cc)
|
||||
* [EIGHT.py](./EIGHT.py)
|
||||
* [manacher.py](./manacher.py)
|
||||
* [markov.py](./markov.py)
|
||||
* [sort](./sort)
|
||||
* [binaryTree.py](./sort/binaryTree.py)
|
||||
* [heapSort.py](./sort/heapSort.py)
|
||||
* [quickSort.py](./sort/quickSort.py)
|
||||
* [radixSort.py](./sort/radixSort.py)
|
||||
* [select.py](./sort/select.py)
|
||||
* [shellSort.py](./sort/shellSort.py)
|
||||
* [sunday.py](./sunday.py)
|
||||
* [README.md](./README.md)
|
|
@ -1,81 +0,0 @@
|
|||
''' mbinary
|
||||
#########################################################################
|
||||
# File : steganography_to_do.py
|
||||
# Author: mbinary
|
||||
# Mail: zhuheqin1@gmail.com
|
||||
# Blog: https://mbinary.coding.me
|
||||
# Github: https://github.com/mbinary
|
||||
# Created Time: 2018-07-06 15:57
|
||||
# Description:
|
||||
#########################################################################
|
||||
'''
|
||||
|
||||
from PIL import Image
|
||||
from skimage import color
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
import math
|
||||
import argparse
|
||||
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('picture')
|
||||
parser.add_argument('-f','file')
|
||||
parser.add_argument('-s','string')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
PIC = args.picture
|
||||
FILE = args.file
|
||||
STR = args.string
|
||||
|
||||
|
||||
class steganography:
|
||||
def __init__(self,picture):
|
||||
self.pic = poicture
|
||||
|
||||
def handlePixel(self,target,attach):
|
||||
'''对一个像素进行隐写 ,attach是要处理的数值,允许在0~9'''
|
||||
a,b,c = target
|
||||
pa,pb,pc = attach
|
||||
return a%10+pa,b%10+pb,c%10+pc
|
||||
def d2n(self,n,base=16):
|
||||
''' num of base_n(n<36) to decimal'''
|
||||
dic = {i:chr(i+ord('0')) for i in range(10)}
|
||||
if base>10:
|
||||
dic.update({i+10:chr(i+ord('A')) for i in range(26)})
|
||||
rst=[]
|
||||
while n!=0:
|
||||
i=int(n/base)
|
||||
rst.append(dic[n-i*base])
|
||||
n=i
|
||||
return ''.join(rst[::-1])
|
||||
def changeBody(self,path):
|
||||
self.pic = path
|
||||
def encryptPic(self,content,base =8):
|
||||
'''将bytes内容content隐写到self.picture中 base can be different value, default 8'''
|
||||
body = np .array (Image.open(self.pic))
|
||||
attach = np.array(content)
|
||||
r,c, _ = body.shape
|
||||
ar,ac,_ = attach.shape
|
||||
|
||||
raise Exception('信息量太大,不能隐写在此图片中,换张更大的图片')
|
||||
def encryptStr(self,content):
|
||||
body = np.array (Image.open(self.pic))
|
||||
r,c,d = body.shape
|
||||
btay = bytearray(content)
|
||||
length = len(btay)
|
||||
if length*8 > (r-1)*c:raise Exception('信息量太大,不能隐写在此图片中,换张更大的图片')
|
||||
def getContent(self,file=None,s=None):
|
||||
'''get the bytes , file is prior to str'''
|
||||
byte = b''
|
||||
if not file:
|
||||
if not s:
|
||||
s = input('输入要隐写的信息')
|
||||
byte = encode(STR,'utf-8')
|
||||
else:byte = open(FILE,'wb').read()
|
||||
return byte
|
||||
|
||||
if __name__ =='__main__':
|
||||
|
||||
PIC
|
|
@ -1,25 +0,0 @@
|
|||
# 数据结构的实现
|
||||
# 索引
|
||||
* [.](.)
|
||||
* [allOone](./allOone)
|
||||
* [allOone.py](./allOone/allOone.py)
|
||||
* [test.py](./allOone/test.py)
|
||||
* [binaryHeap.py](./binaryHeap.py)
|
||||
* [binaryIndexedTree.cc](./binaryIndexedTree.cc)
|
||||
* [binaryTree.py](./binaryTree.py)
|
||||
* [hashTable.py](./hashTable.py)
|
||||
* [huffman.cc](./huffman.cc)
|
||||
* [leftHeap.py](./leftHeap.py)
|
||||
* [loserTree.py](./loserTree.py)
|
||||
* [map](./map)
|
||||
* [map.cc](./map/map.cc)
|
||||
* [map.exe](./map/map.exe)
|
||||
* [segTree.cc](./segTree.cc)
|
||||
* [splayTree.py](./splayTree.py)
|
||||
* [stack](./stack)
|
||||
* [stack.cc](./stack/stack.cc)
|
||||
* [stack.exe](./stack/stack.exe)
|
||||
* [stack.o](./stack/stack.o)
|
||||
* [trie.py](./trie.py)
|
||||
* [winnerTree.py](./winnerTree.py)
|
||||
* [README.md](./README.md)
|
Binary file not shown.
|
@ -1,58 +0,0 @@
|
|||
/* mbinary
|
||||
#########################################################################
|
||||
# File : binaryIndexedTree.cc
|
||||
# Author: mbinary
|
||||
# Mail: zhuheqin1@gmail.com
|
||||
# Blog: https://mbinary.coding.me
|
||||
# Github: https://github.com/mbinary
|
||||
# Created Time: 2018-05-19 23:06
|
||||
# Description:
|
||||
#########################################################################
|
||||
*/
|
||||
|
||||
class bit
|
||||
{
|
||||
int n;
|
||||
int *p;
|
||||
public:
|
||||
bit(int *,int);
|
||||
~bit();
|
||||
int init(int,int,bool);
|
||||
int getSum(int a,int b){return getSum(a)-getSum(b)};
|
||||
int getSum(int);
|
||||
void update(int,int);
|
||||
};
|
||||
bit::bit(int *a,int j)
|
||||
{
|
||||
p=new int[j+1];
|
||||
n=j;
|
||||
for (int i=0;i<n ;++i )p[i+1]=a[i] ;
|
||||
int i;
|
||||
while(i<n)i*=2;
|
||||
init(1,i,true);
|
||||
}
|
||||
int bit::init(int a,int b,bool isLeft)
|
||||
{
|
||||
if(a==b)return p[k];
|
||||
int l=init(a,(a+b)/2,true);
|
||||
int r=init((a+b)/2+1,b,false);
|
||||
if(isLeft)p[b]=l+r;
|
||||
return p[b];
|
||||
}
|
||||
int bit::getSum(int a)
|
||||
{
|
||||
int rst=0;
|
||||
while(a!=0){
|
||||
rst+=p[a];
|
||||
a-=a&-a;
|
||||
}
|
||||
return rst;
|
||||
}
|
||||
void bit::update(int i , int x)
|
||||
{
|
||||
int delta=x-p[i]
|
||||
while(i<n){
|
||||
p[i] = delta;
|
||||
i+=i&-i;
|
||||
}
|
||||
}
|
|
@ -1,376 +0,0 @@
|
|||
/* mbinary
|
||||
#########################################################################
|
||||
# File : huffman.cc
|
||||
# Author: mbinary
|
||||
# Mail: zhuheqin1@gmail.com
|
||||
# Blog: https://mbinary.coding.me
|
||||
# Github: https://github.com/mbinary
|
||||
# Created Time: 2018-05-19 23:06
|
||||
# Description:
|
||||
#########################################################################
|
||||
*/
|
||||
|
||||
#include<math.h>
|
||||
#include<stdio.h>
|
||||
#include<direct.h>
|
||||
#include<iostream>
|
||||
#include<algorithm>
|
||||
#include<map>
|
||||
#include<windows.h>
|
||||
#include<iomanip>
|
||||
#include<string>
|
||||
#include<vector>
|
||||
#include<queue>
|
||||
#define numDigit 10
|
||||
#define nameLength 50
|
||||
#define starNum 80
|
||||
using namespace std;
|
||||
|
||||
void cat(string s)
|
||||
{
|
||||
FILE* f=fopen(s.c_str(),"rb");
|
||||
cout<<"file content"<<endl;
|
||||
while(!feof(f)){
|
||||
cout<<fgetc(f);
|
||||
}
|
||||
cout<<endl;
|
||||
}
|
||||
string uniFileName(string file)
|
||||
{
|
||||
FILE * check = fopen(file.c_str(),"rb");
|
||||
if(check){
|
||||
char c;
|
||||
cout<<"the file "<<file<<" already exists! continue? [Y/n]:"<<flush;
|
||||
c=cin.get();
|
||||
if(c=='n')exit(0);
|
||||
int p,q;
|
||||
p= file.find('(');
|
||||
q=file.rfind('.');
|
||||
if(q==string::npos)q=file.size();
|
||||
if(p==string::npos)p=q;
|
||||
string name=file.substr(0,p),suffix=file.substr(q,file.size());
|
||||
int n=0;
|
||||
while(true){
|
||||
char s[3];
|
||||
n+=1;
|
||||
itoa(n,s,10);
|
||||
file=(name+"("+s+")"+suffix);
|
||||
FILE* f=fopen(file.c_str(),"rb");
|
||||
if(!f)break;
|
||||
else fclose(f);
|
||||
}
|
||||
}
|
||||
return file;
|
||||
}
|
||||
template<class t1, class t2>
|
||||
void mapprint(map<t1,t2> &f)
|
||||
{
|
||||
for(class map<t1,t2>::iterator i = f.begin();i!=f.end();++i)
|
||||
cout<<i->first<<") : "<<i->second<<endl;
|
||||
}
|
||||
template<typename ky,typename wt>
|
||||
class node
|
||||
{
|
||||
public:
|
||||
ky key;
|
||||
wt val;
|
||||
bool visited;
|
||||
node * left,*right;
|
||||
node(const node &a){val = a.val;key= a.key;visited = a.visited;left= a.left;right=a.right;}
|
||||
node(ky k=0,wt v=0):key(k),val(v),visited(false),left(NULL),right(NULL){};
|
||||
bool operator<(const node<ky,wt> & a)const{return val>a.val;};
|
||||
};
|
||||
template<typename ky,typename wt>
|
||||
class huffman
|
||||
{
|
||||
private:
|
||||
node<ky,wt> root;
|
||||
string res;
|
||||
public:
|
||||
long total(){return root.val;}
|
||||
map<ky,string> encode_map;
|
||||
map<string,ky> decode_map;
|
||||
huffman(map<ky,wt>& mp);
|
||||
void display();
|
||||
string encode(string,long &);
|
||||
string decode(string,long&);
|
||||
void preOrder(node<ky,wt>*,string);
|
||||
};
|
||||
template<typename ky,typename wt>
|
||||
huffman<ky,wt>::huffman(map<ky,wt>& mp)
|
||||
{
|
||||
if(mp.empty()){
|
||||
cout<<"Error! No data!"<<endl;
|
||||
root=NULL;
|
||||
return ;
|
||||
}
|
||||
priority_queue<node<ky,wt> > hp;
|
||||
for(typename map<ky,wt>::iterator i=mp.begin();i!=mp.end();++i){
|
||||
hp.push( node<ky,wt>(i->first,i->second));
|
||||
}
|
||||
int n =hp.size();
|
||||
if(n==1){
|
||||
root = hp.top();
|
||||
return;
|
||||
}
|
||||
while(--n>=1){
|
||||
node<ky,wt> *a = new node<ky,wt>(hp.top());
|
||||
hp.pop();
|
||||
node<ky,wt> *b = new node<ky,wt>(hp.top());
|
||||
hp.pop();
|
||||
node<ky,wt> * tmp = new node<ky,wt>(0,a->val+b->val);
|
||||
tmp->left = a,tmp->right = b;
|
||||
hp.push(*tmp);
|
||||
}
|
||||
root = hp.top();
|
||||
preOrder(&root,string());
|
||||
}
|
||||
template<typename ky,typename wt>
|
||||
void huffman<ky,wt>::preOrder(node<ky, wt>* nd,string s)
|
||||
{
|
||||
if(nd->left == NULL){
|
||||
encode_map[nd->key] =s;
|
||||
decode_map[s] = nd->key;
|
||||
delete nd;
|
||||
return ;
|
||||
}
|
||||
preOrder(nd->left,s+'0');
|
||||
preOrder(nd->right,s+'1');
|
||||
delete nd;
|
||||
}
|
||||
template<typename ky,typename wt>
|
||||
string huffman<ky,wt>::decode(string zipfile_name,long &charNum)
|
||||
{
|
||||
string uniFileName(string);
|
||||
FILE * src = fopen(zipfile_name.c_str(),"rb");
|
||||
char file_name[nameLength];
|
||||
fgets(file_name,nameLength,src);
|
||||
int ct=-1;
|
||||
while(file_name[++ct]!='\n');
|
||||
int pos = zipfile_name.find('.');
|
||||
if(pos==string::npos)pos=zipfile_name.size();
|
||||
string name(zipfile_name.substr(0,pos)) ,suffix(file_name,file_name+ct),file(name+suffix);
|
||||
file=uniFileName(file);
|
||||
cout<<"extracting compressed file :"<<zipfile_name<<endl;
|
||||
FILE * f = fopen(file.c_str(),"wb");
|
||||
char t[numDigit];
|
||||
fgets(t,numDigit,src);
|
||||
int sz=atoi(t);
|
||||
char code[sz];
|
||||
fread(code,sz,1,src);
|
||||
int idx=0;
|
||||
for(int i =0;i<sz;++i ){
|
||||
if(code[i]==' '){
|
||||
decode_map[string(code+idx,code+i)]=code[++i];
|
||||
idx=i+1;
|
||||
}
|
||||
}
|
||||
for(int i=0;i<starNum;++i)cout<<"@";
|
||||
cout<<endl;
|
||||
char c;
|
||||
long cur=charNum,gap=charNum/starNum;
|
||||
while(cur){
|
||||
c=fgetc(src);
|
||||
if(!((--cur)%gap))cout<<"@"<<flush;
|
||||
for(int i =0;i<8;++i){
|
||||
if(c&(1<<i))res.append(1,'1');
|
||||
else res.append(1,'0');
|
||||
if(decode_map.count(res)!=0){
|
||||
fputc(decode_map[res],f);
|
||||
res.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
cout<<endl;
|
||||
c=fgetc(src);
|
||||
int dgt=fgetc(src);
|
||||
cout<<feof(f);
|
||||
if((int)dgt!=-1 ){
|
||||
for(int i =0;i<dgt;++i){
|
||||
if(c&(1<<i))res.append(1,'1');
|
||||
else res.append(1,'0');
|
||||
if(decode_map.count(res)!=0){
|
||||
fputc(decode_map[res],f);
|
||||
res.clear();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
fclose(src);
|
||||
fclose(f);
|
||||
cout<<"get "<<file <<" successfully"<<endl;
|
||||
return file;
|
||||
}
|
||||
template<typename ky,typename wt>
|
||||
string huffman<ky,wt>::encode(string file_name,long &charNum)
|
||||
{
|
||||
charNum=0;
|
||||
string uniFileName(string);
|
||||
int pos =file_name.rfind('.');
|
||||
if(pos==string::npos)pos=file_name.size();
|
||||
string zipfile = file_name.substr(0,pos)+string(".zzip");
|
||||
zipfile = uniFileName(zipfile);
|
||||
cout<<"generating zip file :"<<zipfile<<endl;
|
||||
FILE * dst = fopen(zipfile.c_str(),"wb");
|
||||
FILE * f = fopen(file_name.c_str(),"rb");
|
||||
fputs(file_name.substr(pos).c_str(),dst);
|
||||
fputc('\n',dst);
|
||||
string data;
|
||||
for(class map<string,ky>::iterator i=decode_map.begin();i!=decode_map.end() ;++i ){
|
||||
data.append((i->first));
|
||||
data.append(" ");
|
||||
data+=(i->second);
|
||||
}
|
||||
int data_size = data.size(); // calculate the size of the code_data
|
||||
char sz[numDigit];
|
||||
itoa(data_size,sz,numDigit);
|
||||
int ct=0;
|
||||
for(;sz[ct];++ct)fputc(sz[ct],dst);
|
||||
fputc('\n',dst);
|
||||
fwrite(data.c_str(),data_size,1,dst);
|
||||
int sum=0,digit=0,num;
|
||||
string code8;
|
||||
for(int i=0;i<starNum;++i)cout<<"@";
|
||||
cout<<endl;
|
||||
long gap=root.val/starNum,cur=0;
|
||||
while(!feof(f)){
|
||||
code8=encode_map[fgetc(f)];
|
||||
if(!((++cur)%gap))cout<<"@";
|
||||
for(int i=0;i<code8.size();++i){
|
||||
if(code8[i]=='1')sum += 1<<(digit); //mistake if(tmp[j])
|
||||
++digit;
|
||||
if(digit==8){
|
||||
++charNum;
|
||||
fputc(sum,dst);
|
||||
digit=sum=0;
|
||||
}
|
||||
}
|
||||
}
|
||||
cout<<endl;
|
||||
if(digit!=0){ //mark
|
||||
fputc(sum,dst);
|
||||
fputc(digit,dst);
|
||||
}
|
||||
fclose(f);
|
||||
fclose(dst);
|
||||
cout<<"compress "<<file_name <<" successfully"<<endl;
|
||||
return zipfile;
|
||||
}
|
||||
template<typename ky,typename wt>
|
||||
void huffman<ky,wt>::display()
|
||||
{
|
||||
cout<<"the encoding map,huffman codes are as bellow:"<<endl;
|
||||
for (typename map<ky,string>::iterator i=encode_map.begin();i!=encode_map.end() ;++i )
|
||||
cout<<i->first<<"("<<(int)i->first<<"):"<<i->second<<endl;
|
||||
}
|
||||
bool handle_one(string file_name,vector<long> &origin,vector<long> &compressed)
|
||||
{
|
||||
int name_length = file_name.size();
|
||||
FILE *src=fopen(file_name.c_str(),"rb");
|
||||
cout<<"opening "<<file_name<<"..."<<endl;
|
||||
if(!src){
|
||||
cout<<"Path Error! Opening "<<file_name<<" Failed"<<endl;
|
||||
origin.push_back(0);
|
||||
compressed.push_back(0);
|
||||
return false;
|
||||
}
|
||||
char cur;
|
||||
map<char,long> mp;
|
||||
while(!feof(src)){
|
||||
fread(&cur,sizeof(char),1,src);
|
||||
if(mp.count(cur)){
|
||||
mp[cur]+=1;
|
||||
}
|
||||
else mp[cur]=1;
|
||||
}
|
||||
fclose(src);
|
||||
huffman<char,long> hf(mp);
|
||||
long sz;
|
||||
string s(hf.encode(file_name,sz));
|
||||
origin.push_back(hf.total()),compressed.push_back(sz);
|
||||
cout<<"\ncontinue to uncompress? [Y/n]"<<endl;
|
||||
char c=cin.get();
|
||||
if(c=='n')return true;
|
||||
hf.decode(s,sz);
|
||||
return true;
|
||||
}
|
||||
bool isSep(char c)
|
||||
{
|
||||
return c==' '||c=='\n'||c=='\t'||c==',';
|
||||
}
|
||||
void splitToVec(char * s,vector<string>& v)
|
||||
{
|
||||
int i=0,last=0;
|
||||
for(;s[i];++i){
|
||||
if(isSep(s[i])){
|
||||
v.push_back(string(s+last,s+i));
|
||||
while(s[++i]&&isSep(s[i]));
|
||||
last=i;
|
||||
}
|
||||
}
|
||||
if(s[last])v.push_back(string(s+last,s+i));
|
||||
}
|
||||
bool lenStr(string &a,string &b)
|
||||
{
|
||||
return a.size()<b.size();
|
||||
}
|
||||
void go(vector<string> & names)
|
||||
{
|
||||
vector<long> originSize,compressedSize;
|
||||
vector<int> deltaTime;
|
||||
double last;
|
||||
vector<bool> indicator;
|
||||
bool bl;
|
||||
for(vector<string>::iterator i=names.begin();i!=names.end();++i){
|
||||
last=GetTickCount();
|
||||
bl=handle_one(*i,originSize,compressedSize);
|
||||
indicator.push_back(bl);
|
||||
deltaTime.push_back(GetTickCount()-last);
|
||||
}
|
||||
cout<<"\ndealt file number "<<originSize.size()<<fixed<<setprecision(2)<<endl;
|
||||
vector<string>::iterator p=max_element(names.begin(),names.end(),lenStr);
|
||||
int len = p->size()+2;
|
||||
for(int i =0;i<names.size();++i){
|
||||
if(! indicator[i]){continue;}
|
||||
cout<<names[i]<<string(len-names[i].size(),' ');
|
||||
cout<<deltaTime[i]<<"ms "<<compressedSize[i]/1024.0<<"KB/"<<originSize[i]/1024.0<<"KB :";
|
||||
cout<<compressedSize[i]*100.0/originSize[i]<<"%"<<endl;
|
||||
}
|
||||
cout<<endl;
|
||||
system("pause");
|
||||
system("pause");
|
||||
}
|
||||
int main(int argv,char ** argc)
|
||||
{
|
||||
_chdir("C:\\Users\\mbinary\\Desktop\\dataStructrue\\huffman");
|
||||
char cwd[50];
|
||||
cout<<getcwd(cwd,50)<<endl;
|
||||
string file1("GitHubDesktopSetup.exe");
|
||||
string file("δ.mp4");
|
||||
vector<string> names;
|
||||
if(argv>1){
|
||||
for(int i=1;i<argv;++i){
|
||||
names.push_back(argc[i]);
|
||||
}
|
||||
go(names);
|
||||
names.clear();
|
||||
}
|
||||
char mk;
|
||||
while(1){
|
||||
char s[201];
|
||||
cout<<"input file names separated by space "<<endl;
|
||||
cout<<"OR press enter to use the default file:"<<file<<endl;
|
||||
if(cin.peek()=='\n')names.push_back(file);
|
||||
else {
|
||||
cin.getline(s,200);
|
||||
splitToVec(s,names);
|
||||
}
|
||||
cout<<endl;
|
||||
go(names);
|
||||
cout<<"continue to compress or uncompress files? [Y/n]:"<<flush;
|
||||
mk= cin.get();
|
||||
if(mk=='n')break;
|
||||
names.clear();
|
||||
}
|
||||
return 0;
|
||||
}
|
|
@ -12,15 +12,15 @@
|
|||
|
||||
#include<math.h>
|
||||
#include<stdio.h>
|
||||
#include<direct.h>
|
||||
#include<iostream>
|
||||
#include<algorithm>
|
||||
#include<map>
|
||||
#include<windows.h>
|
||||
#include<unistd.h>
|
||||
#include<iomanip>
|
||||
#include<string>
|
||||
#include<vector>
|
||||
#include<queue>
|
||||
#include<sys/time.h>
|
||||
#define numDigit 10
|
||||
#define nameLength 50
|
||||
#define starNum 80
|
||||
|
@ -53,7 +53,7 @@ string uniFileName(string file)
|
|||
while(true){
|
||||
char s[3];
|
||||
n+=1;
|
||||
itoa(n,s,10);
|
||||
snprintf(s,3,"%d",n);
|
||||
file=(name+"("+s+")"+suffix);
|
||||
FILE* f=fopen(file.c_str(),"rb");
|
||||
if(!f)break;
|
||||
|
@ -223,7 +223,7 @@ string huffman<ky,wt>::encode(string file_name,long &charNum)
|
|||
}
|
||||
int data_size = data.size(); // calculate the size of the code_data
|
||||
char sz[numDigit];
|
||||
itoa(data_size,sz,numDigit);
|
||||
snprintf(sz,numDigit,"%d",data_size);
|
||||
int ct=0;
|
||||
for(;sz[ct];++ct)fputc(sz[ct],dst);
|
||||
fputc('\n',dst);
|
||||
|
@ -322,31 +322,32 @@ void go(vector<string> & names)
|
|||
vector<bool> indicator;
|
||||
bool bl;
|
||||
for(vector<string>::iterator i=names.begin();i!=names.end();++i){
|
||||
last=GetTickCount();
|
||||
struct timeval tv;
|
||||
gettimeofday(&tv,NULL);
|
||||
last=tv.tv_sec;
|
||||
bl=handle_one(*i,originSize,compressedSize);
|
||||
indicator.push_back(bl);
|
||||
deltaTime.push_back(GetTickCount()-last);
|
||||
gettimeofday(&tv,NULL);
|
||||
deltaTime.push_back(tv.tv_sec-last);
|
||||
}
|
||||
cout<<"\ndealt file number "<<originSize.size()<<fixed<<setprecision(2)<<endl;
|
||||
cout<<"\nDealt file number "<<originSize.size()<<fixed<<setprecision(2)<<endl;
|
||||
vector<string>::iterator p=max_element(names.begin(),names.end(),lenStr);
|
||||
int len = p->size()+2;
|
||||
for(int i =0;i<names.size();++i){
|
||||
if(! indicator[i]){continue;}
|
||||
cout<<names[i]<<string(len-names[i].size(),' ');
|
||||
cout<<deltaTime[i]<<"ms "<<compressedSize[i]/1024.0<<"KB/"<<originSize[i]/1024.0<<"KB :";
|
||||
cout<<deltaTime[i]<<"s "<<compressedSize[i]/1024.0<<"KB/"<<originSize[i]/1024.0<<"KB :";
|
||||
cout<<compressedSize[i]*100.0/originSize[i]<<"%"<<endl;
|
||||
}
|
||||
cout<<endl;
|
||||
system("pause");
|
||||
system("pause");
|
||||
}
|
||||
int main(int argv,char ** argc)
|
||||
{
|
||||
char cwd[50];
|
||||
cout<<getcwd(cwd,50)<<endl;
|
||||
string file1("GitHubDesktopSetup.exe");
|
||||
string file("δ.mp4");
|
||||
vector<string> names;
|
||||
string file;
|
||||
if(argv>1){
|
||||
for(int i=1;i<argv;++i){
|
||||
names.push_back(argc[i]);
|
||||
|
@ -357,8 +358,7 @@ int main(int argv,char ** argc)
|
|||
char mk;
|
||||
while(1){
|
||||
char s[201];
|
||||
cout<<"input file names separated by space "<<endl;
|
||||
cout<<"OR press enter to use the default file:"<<file<<endl;
|
||||
cout<<"Input file names separated by space "<<endl;
|
||||
if(cin.peek()=='\n')names.push_back(file);
|
||||
else {
|
||||
cin.getline(s,200);
|
||||
|
@ -366,7 +366,7 @@ int main(int argv,char ** argc)
|
|||
}
|
||||
cout<<endl;
|
||||
go(names);
|
||||
cout<<"continue to compress or uncompress files? [Y/n]:"<<flush;
|
||||
cout<<"Continue? [Y/n]:"<<flush;
|
||||
mk= cin.get();
|
||||
if(mk=='n')break;
|
||||
names.clear();
|
|
@ -10,6 +10,7 @@
|
|||
#########################################################################
|
||||
'''
|
||||
|
||||
from winnerTree import winnerTree
|
||||
class loserTree:
|
||||
'''if i<=lowExt p = (i+offset)//2
|
||||
else p = (i+n-1-lowExt)//2
|
||||
|
|
Binary file not shown.
|
@ -10,13 +10,21 @@
|
|||
#########################################################################
|
||||
*/
|
||||
|
||||
#include<stdio.h>
|
||||
#include<string.h>
|
||||
#include<math.h>
|
||||
#include<cstdlib>
|
||||
#include<cstdio>
|
||||
#include<cstring>
|
||||
#include<cmath>
|
||||
#include<malloc.h>
|
||||
#include<map>
|
||||
using namespace std;
|
||||
|
||||
#if defined(__linux__)
|
||||
#define LINUX true
|
||||
#elif defined(_WIN32)
|
||||
#define LINUX false
|
||||
#endif
|
||||
|
||||
|
||||
bool isZero(double a)
|
||||
{
|
||||
if((a<0.00001)&&-a<0.00001)
|
||||
|
@ -295,7 +303,8 @@ void loop()
|
|||
menu();
|
||||
}
|
||||
else if(op == 6){
|
||||
system("cls");
|
||||
if(LINUX) system("clear");
|
||||
else system("cls");
|
||||
menu();
|
||||
}
|
||||
else if(op == 10){
|
|
@ -166,8 +166,5 @@ def menu():
|
|||
print('10.menu')
|
||||
print('11.exit')
|
||||
|
||||
def go():
|
||||
menu()
|
||||
|
||||
if __name__ == '__main__':
|
||||
go()
|
||||
pass
|
|
@ -1,55 +0,0 @@
|
|||
/* mbinary
|
||||
#########################################################################
|
||||
# File : segTree.cc
|
||||
# Author: mbinary
|
||||
# Mail: zhuheqin1@gmail.com
|
||||
# Blog: https://mbinary.coding.me
|
||||
# Github: https://github.com/mbinary
|
||||
# Created Time: 2018-05-19 23:06
|
||||
# Description:
|
||||
#########################################################################
|
||||
*/
|
||||
|
||||
#include<stdio.h>
|
||||
template<class type>
|
||||
bool operator <(type x,type y){return x<y;}
|
||||
template<class type>
|
||||
class segTree
|
||||
{
|
||||
int size;
|
||||
type *p;
|
||||
public:
|
||||
segTree(int n=1);
|
||||
~segTree();
|
||||
void update(int i,type x);
|
||||
type getMin(int a,int b){return find(a,b,1,size,1);}
|
||||
type find(int a,int b,int i,int j,int);
|
||||
};
|
||||
template<class type >
|
||||
segTree<type>::segTree(int n):size(1)
|
||||
{
|
||||
while(size<n)size*=2;
|
||||
p = new type[2*size-1];
|
||||
for (int i=0;i<2*size-1 ;++i )p[i]=MAX;
|
||||
}
|
||||
template<class type >
|
||||
segTree<type>::~segTree(){delete p;}
|
||||
template<class type>
|
||||
void segTree<type>::update(int i,type x)
|
||||
{
|
||||
i+=size-1;
|
||||
p[i]=x;
|
||||
while(i!=0){
|
||||
i/=2;
|
||||
p[i]=p[i*2]<p[i*2+1]?p[i*2]:p[i*2+1];
|
||||
}
|
||||
}
|
||||
template<class type>
|
||||
type segTree<type>::find(int a,int b,int i , int j,int k)
|
||||
{
|
||||
if(b<i}}j<a)return MAX;// to implement
|
||||
if (a<=i&&j<=b)return p[k];
|
||||
type l= find(a,b,i,(i+j)/2,2*k);
|
||||
type r= find(a,b,(i+j)/2+1,j,2*k+1);
|
||||
return l>r ?l:r;
|
||||
}
|
|
@ -1,115 +0,0 @@
|
|||
/* mbinary
|
||||
#########################################################################
|
||||
# File : stack.cc
|
||||
# Author: mbinary
|
||||
# Mail: zhuheqin1@gmail.com
|
||||
# Blog: https://mbinary.coding.me
|
||||
# Github: https://github.com/mbinary
|
||||
# Created Time: 2018-04-26 10:33
|
||||
# Description:
|
||||
#########################################################################
|
||||
*/
|
||||
|
||||
#include<malloc.h>
|
||||
#include<stdio.h>
|
||||
#include<vector>
|
||||
#define SZ 50
|
||||
using namespace std;
|
||||
template<typename type>
|
||||
class stack
|
||||
{
|
||||
int capacity;
|
||||
type *bottom,*top;
|
||||
public:
|
||||
stack(int n = SZ);
|
||||
stack( stack &);
|
||||
stack(int,type);
|
||||
stack(vector<type> &);
|
||||
type pop();
|
||||
int cp();
|
||||
void push(type);
|
||||
bool empty();
|
||||
type getTop();
|
||||
};
|
||||
template<typename type>
|
||||
stack<type>::stack(int n):capacity(n)
|
||||
{
|
||||
bottom = new type[capacity+1];
|
||||
top = bottom;
|
||||
}
|
||||
|
||||
template<typename type>
|
||||
stack<type>::stack(int n,type x):capacity(n*2)
|
||||
{
|
||||
bottom = new type[capacity+1];
|
||||
top = bottom;
|
||||
for(int i = 0;i<n;++i)*(++top) = x;
|
||||
}
|
||||
template<typename type>
|
||||
stack<type>::stack(vector<type> &vc):capacity (vc.size()*2)
|
||||
{
|
||||
bottom = new type[capacity+1];
|
||||
top = bottom;
|
||||
for(int i = 0;i!=vc.size();++i){
|
||||
push(vc[i]);
|
||||
}
|
||||
}
|
||||
template<typename type>
|
||||
stack<type>::stack(stack &s):capacity(s.capacity)
|
||||
{
|
||||
bottom = new type[capacity+1];
|
||||
top = bottom;
|
||||
for(type *p= s.bottom;p!=s.top;)*(++top) = *(++p);
|
||||
}
|
||||
template<typename type>
|
||||
int stack<type>::cp()
|
||||
{
|
||||
return capacity;
|
||||
}
|
||||
template<typename type>
|
||||
bool stack<type>::empty()
|
||||
{
|
||||
return bottom == top;
|
||||
}
|
||||
template<typename type>
|
||||
type stack<type>::getTop()
|
||||
{
|
||||
return *top;
|
||||
}
|
||||
template<typename type>
|
||||
type stack<type>::pop()
|
||||
{
|
||||
if(bottom == top){
|
||||
printf("the stack is empty now\n");
|
||||
return 0;
|
||||
}else{
|
||||
return *(top--);
|
||||
}
|
||||
}
|
||||
template<typename type>
|
||||
void stack<type>::push(type x)
|
||||
{
|
||||
if(capacity == top-bottom){
|
||||
bottom = (type *)realloc(bottom,sizeof(type)*(2*capacity+1));
|
||||
top = bottom+capacity;
|
||||
}
|
||||
*(++top) = x;
|
||||
}
|
||||
int main()
|
||||
{
|
||||
stack<char> sc(5,'z'),scc(sc);
|
||||
printf("stack copy\n");
|
||||
while(!scc.empty()){
|
||||
printf("%c\n",scc.pop());
|
||||
}
|
||||
vector<double> vc(50,2.3);
|
||||
stack<double> sd(vc);
|
||||
sd.push(3.4);
|
||||
printf("gettop%lf\n",sd.getTop());
|
||||
printf("vec copy\n");
|
||||
while(!sd.empty()){
|
||||
printf("%lf\n",sd.pop());
|
||||
}
|
||||
printf("empty %d\ncapacity%d",sd.empty(),sd.cp());
|
||||
return 0;
|
||||
}
|
Binary file not shown.
|
@ -1,38 +0,0 @@
|
|||
\relax
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {1}需求分析}{2}}
|
||||
\@writefile{toc}{\contentsline {paragraph}{1}{2}}
|
||||
\@writefile{toc}{\contentsline {paragraph}{2}{2}}
|
||||
\@writefile{toc}{\contentsline {paragraph}{3}{2}}
|
||||
\@writefile{toc}{\contentsline {paragraph}{4}{2}}
|
||||
\@writefile{toc}{\contentsline {paragraph}{5}{2}}
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {2}概要设计}{2}}
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {2.1}结点node}{2}}
|
||||
\@writefile{toc}{\contentsline {paragraph}{数据对象}{2}}
|
||||
\@writefile{toc}{\contentsline {paragraph}{数据关系}{2}}
|
||||
\@writefile{toc}{\contentsline {paragraph}{基本操作}{2}}
|
||||
\@writefile{toc}{\contentsline {subparagraph}{node()}{2}}
|
||||
\@writefile{toc}{\contentsline {subparagraph}{node( const node\& nd}{2}}
|
||||
\@writefile{toc}{\contentsline {subparagraph}{operator<}{2}}
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {2.2}huffman树}{3}}
|
||||
\@writefile{toc}{\contentsline {paragraph}{数据对象}{3}}
|
||||
\@writefile{toc}{\contentsline {paragraph}{数据关系}{3}}
|
||||
\@writefile{toc}{\contentsline {paragraph}{基本操作}{3}}
|
||||
\@writefile{toc}{\contentsline {subparagraph}{huffman( map)}{3}}
|
||||
\@writefile{toc}{\contentsline {subparagraph}{encode(string)}{3}}
|
||||
\@writefile{toc}{\contentsline {subparagraph}{decode(string)}{3}}
|
||||
\@writefile{toc}{\contentsline {subparagraph}{preorder()}{3}}
|
||||
\@writefile{toc}{\contentsline {subparagraph}{display}{3}}
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {3}详细设计}{3}}
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {3.1}编码,解码算法}{3}}
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {3.2}输出进度条}{7}}
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {3.3}改变文件名}{7}}
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {3.4}统计信息}{7}}
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {4}调试分析}{8}}
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {4.1}编码信息的存储}{8}}
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {4.2}最后一个字节}{8}}
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {4.3}文件名的处理}{8}}
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {5}用户手册}{8}}
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {6}测试结果}{9}}
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {6.1}文本文件}{9}}
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {6.2}二进制文件1}{10}}
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {6.3}二进制文件2}{11}}
|
Binary file not shown.
File diff suppressed because it is too large
Load Diff
Binary file not shown.
Binary file not shown.
|
@ -1,155 +0,0 @@
|
|||
''' mbinary
|
||||
#########################################################################
|
||||
# File : directed.py
|
||||
# Author: mbinary
|
||||
# Mail: zhuheqin1@gmail.com
|
||||
# Blog: https://mbinary.coding.me
|
||||
# Github: https://github.com/mbinary
|
||||
# Created Time: 2018-04-25 22:28
|
||||
# Description:
|
||||
#########################################################################
|
||||
'''
|
||||
|
||||
from collections import deque
|
||||
class vertex:
|
||||
def __init__(self,mark,val=None ,firstEdge = None):
|
||||
self.mark = mark
|
||||
self.val = val
|
||||
self.firstEdge = firstEdge
|
||||
self.isVisited = False
|
||||
def __str__(self):
|
||||
try:
|
||||
int(self.mark)
|
||||
return 'v'+str(self.mark)
|
||||
except:return str(self.mark)
|
||||
def __repr__(self):
|
||||
li=[]
|
||||
arc= self.firstEdge
|
||||
while arc!=None:
|
||||
li.append(arc)
|
||||
arc= arc.outNextEdge
|
||||
return str(self)+ ' to:'+str([str(i.inArrow) for i in li])
|
||||
class edge:
|
||||
def __init__(self,outArrow,inArrow,outNextEdge = None,inNextEdge = None, weight = 1):
|
||||
self.weight = weight
|
||||
self.inNextEdge = inNextEdge
|
||||
self.outNextEdge = outNextEdge
|
||||
self.outArrow = outArrow
|
||||
self.inArrow=inArrow
|
||||
self.isVisited = False
|
||||
def __str__(self):
|
||||
return '--'+str(self.weight)+'-->'
|
||||
def __repr__(self):
|
||||
return str(self)
|
||||
class graph:
|
||||
def __init__(self):
|
||||
self.vertexs = {}
|
||||
self.edges = {}
|
||||
def __getitem__(self,i):
|
||||
return self.vertexs[i]
|
||||
def __setitem__(selfi,x):
|
||||
self.vertexs[i]= x
|
||||
def __iter__(self):
|
||||
return iter(self.vertexs.values())
|
||||
def __bool__(self):
|
||||
return len(self.vertexs)!=0
|
||||
def addVertex(self,i):
|
||||
if not (i,vertex) and i not in self.vertexs:self.vertexs[i]= vertex(i)
|
||||
if isinstance(i,vertex) and i not in self.vertexs:self.vertexs[i.mark]= i
|
||||
def isConnected(self,v,u):
|
||||
v = self.__getVertex(v)
|
||||
u = self.__getVertex(u)
|
||||
arc= v.firstEdge
|
||||
while arc!=None:
|
||||
if arc.inArrow==u:return True
|
||||
arc = arc.inNextEdge
|
||||
return False
|
||||
def __getVertex(self,v):
|
||||
if not isinstance(v,vertex):
|
||||
if v not in self.vertexs:
|
||||
self.vertexs[v]=vertex(v)
|
||||
return self.vertexs[v]
|
||||
return v
|
||||
def addEdge(self,v,u,weight = 1):
|
||||
v = self.__getVertex(v)
|
||||
u = self.__getVertex(u)
|
||||
arc = v.firstEdge
|
||||
while arc!=None: #examine that if v,u have been already connected
|
||||
if arc.inArrow==u: return
|
||||
arc= arc.outNextEdge
|
||||
newEdge = edge(v,u,v.firstEdge,u.firstEdge,weight)
|
||||
self.edges[(v.mark,u.mark)] = newEdge
|
||||
v.firstEdge = newEdge
|
||||
def delEdge(self,v,u):
|
||||
if not isinstance(v,vertex):v= self.vertexs[v]
|
||||
if not isinstance(u,vertex):u= self.vertexs[u]
|
||||
self._unrelated(v,u)
|
||||
del self.edges[(v.mark,u.mark)]
|
||||
def _unrelated(self,v,u):
|
||||
if v.firstEdge==None:return
|
||||
if v.firstEdge.inArrow == u:
|
||||
v.firstEdge =v.firstEdge.outNextEdge
|
||||
else:
|
||||
arc = v.firstEdge
|
||||
while arc.outNextEdge!=None:
|
||||
if arc.outNextEdge.inArrow ==u:
|
||||
arc.outNextEdge = arc.outNextEdge.outNextEdge
|
||||
break
|
||||
def reVisit(self):
|
||||
for i in self.vertexs:
|
||||
self.vertexs[i].isVisited=False
|
||||
for i in self.edges:
|
||||
self.edges[i].isVisited=False
|
||||
def __str__(self):
|
||||
arcs= list(self.edges.keys())
|
||||
arcs=[str(i[0])+'--->'+str(i[1])+' weight:'+str(self.edges[i].weight) for i in arcs]
|
||||
s= '\n'.join(arcs)
|
||||
return s
|
||||
def __repr__(self):
|
||||
return str(self)
|
||||
def notIn(self,v):
|
||||
if (isinstance(v,vertex) and v.mark not in self.vertexs) or v not in self.vertexs:
|
||||
return True
|
||||
return False
|
||||
def minPath(self,v,u):
|
||||
'''dijstra'''
|
||||
self.reVisit()
|
||||
if self.notIn(v) or self.notIn(u):
|
||||
return [],0
|
||||
v = self.__getVertex(v)
|
||||
u = self.__getVertex(u)
|
||||
if v.firstEdge==None:return [],0
|
||||
q=deque([v])
|
||||
last = {i : None for i in self}
|
||||
distance={i : 1<<30 for i in self}
|
||||
distance[v]=0
|
||||
while len(q)!=0:
|
||||
cur= q.popleft()
|
||||
cur.isVisited = True
|
||||
arc = cur.firstEdge
|
||||
while arc!=None:
|
||||
to = arc.inArrow
|
||||
if not to.isVisited:
|
||||
q.append(to)
|
||||
if distance [to] > distance[cur]+arc.weight:
|
||||
last[to]=cur
|
||||
distance[to] =distance[cur]+arc.weight
|
||||
arc= arc.outNextEdge
|
||||
cur = u
|
||||
path=[]
|
||||
while cur!=None and cur!=v:
|
||||
path.append(cur.mark)
|
||||
cur=last[cur]
|
||||
if cur==None:return [], 0
|
||||
path.append(v.mark)
|
||||
return path[::-1],distance[u]
|
||||
def hasVertex(self,mark):
|
||||
return mark in self.vertexs
|
||||
def display(self):
|
||||
print('vertexs')
|
||||
for i in self.vertexs:
|
||||
print(self.vertexs[i].__repr__())
|
||||
print('edges')
|
||||
for i in self.edges:
|
||||
arc=self.edges[i]
|
||||
print(str(arc.outArrow)+str(arc)+str(arc.inArrow))
|
|
@ -1,237 +0,0 @@
|
|||
''' mbinary
|
||||
#########################################################################
|
||||
# File : graph.py
|
||||
# Author: mbinary
|
||||
# Mail: zhuheqin1@gmail.com
|
||||
# Blog: https://mbinary.coding.me
|
||||
# Github: https://github.com/mbinary
|
||||
# Created Time: 2018-04-25 22:28
|
||||
# Description:
|
||||
#########################################################################
|
||||
'''
|
||||
|
||||
from collections import deque
|
||||
import directed
|
||||
class vertex:
|
||||
def __init__(self,mark,val=None):
|
||||
self.mark = mark
|
||||
self.val = val
|
||||
self.edges = {}
|
||||
self.isVisited = False
|
||||
def __getitem__(self,adjVertexMark):
|
||||
return self.edges[adjVertexMark]
|
||||
def __delitem__(self,k):
|
||||
del self.edges[k]
|
||||
def __iter__(self):
|
||||
return iter(self.edges.values())
|
||||
def __str__(self):
|
||||
try:
|
||||
int(self.mark)
|
||||
return 'v'+str(self.mark)
|
||||
except:return str(self.mark)
|
||||
def __repr__(self):
|
||||
return str(self)
|
||||
class edge:
|
||||
def __init__(self,adjVertexs, weight = 1):
|
||||
'''adjVertexs:tuple(v.mark,u.mark)'''
|
||||
self.weight = weight
|
||||
self.adjVertexs = adjVertexs
|
||||
self.isVisted = False
|
||||
def __add__(self,x):
|
||||
return self.weight +x
|
||||
def __radd__(self,x):
|
||||
return self+x
|
||||
def __getitem__(self,k):
|
||||
if k!=0 or k!=1:raise IndexError
|
||||
return self.adjVertexs[k]
|
||||
def __str__(self):
|
||||
return '--'+str(self.weight)+'--'
|
||||
def __repr__(self):
|
||||
return str(self)
|
||||
@property
|
||||
def v(self):
|
||||
return self.adjVertexs[0]
|
||||
@property
|
||||
def u(self):
|
||||
return self.adjVertexs[1]
|
||||
class graph:
|
||||
def __init__(self):
|
||||
self.vertexs = {}
|
||||
self.edges = {}
|
||||
def __getitem__(self,i):
|
||||
return self.vertexs[i]
|
||||
def __setitem__(selfi,x):
|
||||
self.vertexs[i]= x
|
||||
def __iter__(self):
|
||||
return iter(self.vertexs)
|
||||
def __bool__(self):
|
||||
return len(self.vertexs)!=0
|
||||
def addVertex(self,v):
|
||||
if not isinstance(v,vertex) and v not in self.vertexs:self.vertexs[v]= vertex(v)
|
||||
if isinstance(v,vertex) and v not in self.vertexs:self.vertexs[v.mark]= v
|
||||
|
||||
def __getVertex(self,v):
|
||||
if not isinstance(v,vertex):
|
||||
if v not in self.vertexs:
|
||||
self.vertexs[v]=vertex(v)
|
||||
return self.vertexs[v]
|
||||
return v
|
||||
def addEdge(self,v,u,weight = 1):
|
||||
v = self.__getVertex(v)
|
||||
u = self.__getVertex(u)
|
||||
for arc in v:
|
||||
if u in arc.adjVertexs:return #examine that if v,u have been already connected
|
||||
vertexs = (v,u)
|
||||
newEdge = edge (vertexs,weight)
|
||||
self.edges[vertexs] = newEdge
|
||||
v.edges[u] = newEdge
|
||||
u.edges[v] = newEdge
|
||||
def delEdge(self,v,u):
|
||||
if not isinstance(v,vertex):v= self.vertexs[v]
|
||||
if not isinstance(u,vertex):u= self.vertexs[u]
|
||||
try:
|
||||
del v[u]
|
||||
del u[v]
|
||||
except:print("error!"+str(v)+','+str(u)+' arent adjacent now')
|
||||
del self.edges[(v,u)]
|
||||
def reVisit(self):
|
||||
for i in self.vertexs.values():
|
||||
i.isVisited = False
|
||||
for i in self.edges.values():
|
||||
i.isVisited = False
|
||||
def __str__(self):
|
||||
arcs= list(self.edges.keys())
|
||||
arcs=[str(i[0])+str(self.edges[i])+str(i[1]) for i in arcs]
|
||||
s= '\n'.join(arcs)
|
||||
return s
|
||||
def __repr__(self):
|
||||
return str(self)
|
||||
def minPath(self,v,u):
|
||||
self.reVisit()
|
||||
v=self.__getVertex(v)
|
||||
u=self.__getVertex(u)
|
||||
q=deque([v])
|
||||
last={i:None for i in self.vertexs.values()}
|
||||
last[v] = 0
|
||||
ds={i:1<<30 for i in self.vertexs.values()}
|
||||
ds[v]=0
|
||||
while len(q)!=0:
|
||||
nd = q.popleft()
|
||||
nd.isVisited=True
|
||||
for edge in nd:
|
||||
tgt=None
|
||||
if edge.v==nd:
|
||||
tgt = edge.u
|
||||
else:tgt = edge.v
|
||||
tmp=ds[nd]+edge
|
||||
if ds[tgt] >tmp:
|
||||
ds[tgt]=tmp
|
||||
last[tgt] = nd
|
||||
if not tgt.isVisited:q.append(tgt)
|
||||
path=[]
|
||||
cur = u
|
||||
while cur !=None and cur.mark!=v.mark:
|
||||
path.append(cur.mark)
|
||||
cur = last[cur]
|
||||
if cur==None:return [],-1
|
||||
path.append(v.mark)
|
||||
return path[::-1],ds[u]
|
||||
def hasCircle(self):
|
||||
pass
|
||||
def display(self):
|
||||
print('vertexs')
|
||||
for i in self.vertexs:
|
||||
print(i,end=' ')
|
||||
print('')
|
||||
print('edges')
|
||||
for i in self.edges:
|
||||
arc=self.edges[i]
|
||||
print(str(arc.v)+str(arc)+str(arc.u))
|
||||
|
||||
def loop(dic):
|
||||
while True:
|
||||
print('input vertexs to get the min distance, input \'exit\' to exit')
|
||||
s=input().strip()
|
||||
if s=='exit':break
|
||||
s=s.split(' ')
|
||||
s=[dic[i] if '0'<=i[0]<='9' else i for i in s]
|
||||
a,b,c=s[0],s[1],None
|
||||
path,d = g.minPath(a,b)
|
||||
path2=None
|
||||
if len(s)==3:
|
||||
c=s[2]
|
||||
path2,d2=g.minPath(b,c)
|
||||
d+=d2
|
||||
if path==[] or path2==[] :
|
||||
if len(s)==3: print(a+' can\'t reach '+c+' via '+b)
|
||||
else: print(a+' can\'t reach '+b)
|
||||
continue
|
||||
if path2!=None:path+=path2[1:]
|
||||
print('distance : ',d)
|
||||
print('path','-->'.join(path))
|
||||
|
||||
|
||||
if __name__ =='__main__':
|
||||
s=input('1. undireted\n2. directed\n')
|
||||
flag=input('name vertex by 1. num(1-index) or 2. string? ').strip()
|
||||
dic={}
|
||||
g = graph()
|
||||
if s=='2': g=directed.graph()
|
||||
v,e=input('input vertex num & edge num: ').strip().split(' ')
|
||||
v,e=int(v),int(e)
|
||||
if flag=='1':
|
||||
for i in range(v):
|
||||
tmp=str(i+1)
|
||||
dic[tmp]=tmp
|
||||
g.addVertex(tmp)
|
||||
else:
|
||||
print('input vertex name line by line')
|
||||
for i in range(v):
|
||||
dic[str(i+1)]=input().strip()
|
||||
g.addVertex(dic[str(i+1)])
|
||||
print('input edge info line by line')
|
||||
for i in range(e):
|
||||
li=input().strip().split(' ')
|
||||
a,b,w=li[0],li[1],1
|
||||
if len(li)==3:w=int(li[2])
|
||||
a,b=dic[a],dic[b]
|
||||
g.addEdge(a,b,w)
|
||||
print('you\'ve build graph :')
|
||||
g.display()
|
||||
loop(dic)
|
||||
'''
|
||||
6 6
|
||||
1 2 5
|
||||
1 3 1
|
||||
2 6 1
|
||||
2 5 1
|
||||
4 5 2
|
||||
3 4 1
|
||||
1 5
|
||||
'''
|
||||
|
||||
'''
|
||||
6 10
|
||||
NewYork
|
||||
LA
|
||||
BeiJing
|
||||
HeFei
|
||||
SiChuan
|
||||
Paris
|
||||
2 1
|
||||
5 3
|
||||
6 1
|
||||
3 1
|
||||
4 4
|
||||
1 3
|
||||
2 1
|
||||
5 1
|
||||
2 4
|
||||
3 4
|
||||
SiChuan NewYork
|
||||
Paris HeFei
|
||||
V4<---V3<---V2<---V1
|
||||
3
|
||||
V4<---V3<---V2
|
||||
2
|
||||
'''
|
Binary file not shown.
Binary file not shown.
41
tree_link.py
41
tree_link.py
|
@ -1,41 +0,0 @@
|
|||
# coding: utf-8
|
||||
import os
|
||||
import argparse
|
||||
|
||||
#命令行输入参数处理
|
||||
parser = argparse.ArgumentParser()
|
||||
|
||||
parser.add_argument('-p','--path',default='.')
|
||||
parser.add_argument('-f','--fileinclude',default=False)
|
||||
parser.add_argument('-d','--depth', type = int, default = 2)
|
||||
#获取参数
|
||||
args = parser.parse_args()
|
||||
FILE = args.fileinclude
|
||||
PATH = args.path
|
||||
DEPTH = args.depth
|
||||
|
||||
|
||||
def mklink(path):
|
||||
return '* [{name}]({path})'.format(name=os.path.basename(path),path=path)
|
||||
def clean(paths):
|
||||
ret = []
|
||||
for path in paths:
|
||||
name = os.path.basename(path)
|
||||
if not ( name.startswith('.') or name.startswith('__')):
|
||||
ret.append(path)
|
||||
return ret
|
||||
|
||||
def tree(path='.',depth=2):
|
||||
li = os.listdir(path) if os.path.isdir(path) else [path]
|
||||
items = [os.path.join(path,i) for i in li if not i.startswith('.')]
|
||||
items = clean(items)
|
||||
if not FILE: items = [i for i in items if os.path.isdir(i)]
|
||||
if depth==1:
|
||||
return [mklink(path)] + [' '*4 + mklink(i) for i in items]
|
||||
else:
|
||||
uls = [tree(i,depth-1) for i in items]
|
||||
return [mklink(path)] + [' '*4 + li for ul in uls for li in ul]
|
||||
|
||||
|
||||
if __name__ =='__main__':
|
||||
print('\n'.join(tree(PATH,DEPTH)))
|
Loading…
Reference in New Issue
Block a user