Fork de wikipp, le moteur de wiki en c++, basé sur cppcms. Le fork ajoute la langue française
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

diff.h 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #ifndef DIFF_H
  2. #define DIFF_H
  3. #include <vector>
  4. #include <string>
  5. namespace diff {
  6. typedef std::vector<std::vector<int> > diff_matrix;
  7. template<typename element>
  8. diff_matrix lcs_length(std::vector<element> const &X,std::vector<element> const &Y)
  9. {
  10. int m=X.size();
  11. int n=Y.size();
  12. diff_matrix C(m+1,std::vector<int>(n+1,0));
  13. int i,j;
  14. for(i=1;i<=m;i++) {
  15. for(j=1;j<=n;j++) {
  16. if(X[i-1]==Y[j-1]) {
  17. C[i][j]=C[i-1][j-1]+1;
  18. }
  19. else {
  20. C[i][j]=std::max(C[i][j-1],C[i-1][j]);
  21. }
  22. }
  23. }
  24. return C;
  25. }
  26. template<typename element,typename CNT>
  27. void print_diff(diff_matrix const &C,std::vector<element> const &X,std::vector<element> const &Y,int i,int j,CNT &out)
  28. {
  29. if(i>0 && j>0 && X[i-1]==Y[j-1]){
  30. print_diff(C,X,Y,i-1,j-1,out);
  31. out.push_back(make_pair(0,X[i-1]));
  32. }
  33. else {
  34. if(j>0 && (i==0 || C[i][j-1] >= C[i-1][j])){
  35. print_diff(C,X,Y,i,j-1,out);
  36. out.push_back(make_pair(1,Y[j-1]));
  37. }
  38. else if(i > 0 && (j == 0 || C[i][j-1] < C[i-1][j])) {
  39. print_diff(C,X,Y,i-1,j,out);
  40. out.push_back(make_pair(-1,X[i-1]));
  41. }
  42. }
  43. }
  44. template<typename element,typename CNT>
  45. void diff(std::vector<element> const &X,std::vector<element> const &Y,CNT &out)
  46. {
  47. diff_matrix C=diff::lcs_length(X,Y);
  48. print_diff(C,X,Y,X.size(),Y.size(),out);
  49. }
  50. } // namespace diff
  51. std::vector<std::string> split(std::string const &s)
  52. {
  53. std::vector<std::string> res;
  54. size_t pos=0,pos2=0;
  55. while((pos2=s.find('\n',pos))!=std::string::npos) {
  56. res.push_back(s.substr(pos,pos2-pos));
  57. pos=pos2+1;
  58. }
  59. res.push_back(s.substr(pos));
  60. return res;
  61. }
  62. #endif