Study Questions 15-1
Note that this problem is said to have a direction-free graph, so there is a dynamic programming algorithm to calculate the longest weighted simple path.
Set Dis[u] Dis[u] represents the longest weighted simple path from u u to t T, you can get the following equation:
Dis[u]={0max (u,v) ∈e{w (u,v) +dis[v]}if u=totherwise dis[u]= \begin{cases} 0& \text{if u=t}\\ \max \limits_{(u,v) \in E }\{w (u,v) +dis[v]\} & \text{otherwise} \end{cases}
Using a bottom-up approach
Longest-path (g, S, T) let
DIST[1...N] and NEXT[1...N] is new arrays
topologically sort the vertices of G
for i = 1 to | g.v|
Dist[i] =∞
dist[s] = 0
for each U-topological order, starting from S to each
edge (u,v) ∈g.adj[u]
if Dist[u] + w (u,v) > Dist[v]
dist[v] = Dist[u] + w (u,v)
next[u] = v
print "The Longest distance is" Dist[t]
Print-path (S, T, next)
The time complexity is Θ (v+e) \theta (v+e). Study Questions 15-2
First of all, this problem and the general longest palindrome subsequence seems different, because it gives the character is Carac, the substring is not contiguous in the original string, the general should be returned is ARA.
For this problem, a very simple idea is to find the longest common sub-sequence, first the string reversal, and then the longest common sub-sequence can be.
#include <iostream> #include <string> using Std::cout;
Using Std::cin;
Using Std::endl;
Using Std::string;
void Lcs_length (String &x,string &y,int **b,int **c) {int m = x.size (), n = y.size ();
for (int i = 0; I <= N; i++) c[i][0] = 0;
for (int i = 1; I <= n; i++) c[0][i] = 0;
for (int i = 1, i <= m; i++) {for (int j = 1; J <= N; j + +) {if (x[i-1] = = Y[j-1])
{C[i][j] = c[i-1][j-1] + 1;
B[I][J] = 0;
} else if (C[i-1][j] >= c[i][j-1]) {c[i][j] = c[i-1][j];
B[I][J] = 1;//up} else {c[i][j] = c[i][j-1]; B[I][J] = 2;//left}}}} void Print_lcs (int **b,string &x,int I,int j) {if (i = = 0 | | j
= = 0) return;
if (b[i][j] = = 0) {Print_lcs (b,x,i-1,j-1); Cout << X[i-1];
} else if (b[i][j] = = 1) print_lcs (B,X,I-1,J);
else Print_lcs (b,x,i,j-1);
} int Main () {string x = "character";
String y = x;
for (int i = 0; i < y.size ()/2; i++) {Char temp = y[i];
Y[i] = y[y.size ()-i-1];
Y[y.size ()-i-1] = temp;
} int m = X.size (), n = y.size ();
int **b = new int *[m+1];
int **c = new int *[m+1];
for (int i = 0; I <= m; i++) {B[i] = new int[n+1];
C[i] = new int[n+1];
} lcs_length (X,y,b,c);
Print_lcs (B,x,m,n);
cout << Endl;
for (int i = 0; I <= m; i++) {delete []b[i];
delete []c[i];
} Delete []b;
delete []c;
return 0; }
Study Questions 15-3
First sort by x coordinate, need O (NLGN) O (n\lg N) time, set the ordered point from left to right (P1,P2...PN) (P_1,p_2...p_n), where P1 p_1 is the leftmost point, PN P_n is the most right point.
Define a double-tuning path pi,j, where I≤j p_{i,j}, where I\le J, contains all the p1,p2 ...