实现第五版,王晓东编著的第三章3.5凸多边形最优三角剖分问题的代码。课本62页。
#include<iostream>
#include<cmath>
int x[50],y[50];
using namespace std;
double w(int i,int k,int j);
void MinWeightTriangulation(int n,int **t,int **s);
void Traceback(int i,int j,int **s);
int main(){
cout<<"请输入顶点个数:";
int n;
cin>>n;
int **t=new int *[n];
int **s=new int *[n];
for(int i=0;i<n;i++){
s[i]=new int [n];
t[i]=new int [n];
}
cout<<"请输入各点坐标:";
for(int i=0;i<n;i++){
cin>>x[i]>>y[i];
}
n--;
MinWeightTriangulation(n,t,s);
Traceback(1,n,s);
return 0;
}
double w(int i,int k,int j){
return(sqrt((x[i]-x[k])*(x[i]-x[k])+(y[i]-y[k])*(y[i]-y[k]))
+sqrt((x[k]-x[j])*(x[k]-x[j])+(y[k]-y[j])*(y[k]-y[j]))
+sqrt((x[j]-x[i])*(x[j]-x[i])+(y[j]-y[i])*(y[j]-y[i])));
}
void MinWeightTriangulation(int n,int **t,int **s){
for(int i=1;i<=n;i++) t[i][i]=0;
for(int r=2;r<=n;r++){
for(int i=1;i<=n-r+1;i++){
int j=i+r-1;
t[i][j]=t[i+1][j]+w(i-1,i,j);
s[i][j]=i;
for(int k=i+1;k<i+r-1;k++){
int u=t[i][k]+t[k+1][j]+w(i-1,k,j);
if(u<t[i][j]){
t[i][j]=u;
s[i][j]=k;
}
}
}
}
}
void Traceback(int i,int j,int **s){
if(i==j) return;
Traceback(i,s[i][j],s);
Traceback(s[i][j]+1,j,s);
cout<<"组成最优三角的顶点为:"<<i-1<<" "<<j<<" "<<s[i][j]<<endl;
}