凸多边形最优三角剖分
#include<iostream>
#include<iomanip>
#include<vector>
#include<algorithm>
using namespace std;
class Trianglation
{
public:
Trianglation()
{
cin >> n;
v.assign(n, -1);
for (int i = 0; i < n; i++)
{
int in;
cin >> in;
v[i] = in;
}
vector<int> x;
t.push_back(x);
s.push_back(x);
for (int i = 1; i < n; i++)
{
vector<int> y(n, -1);
t.push_back(y);
s.push_back(y);
}
}
void MinWight()
{
int q = n - 1;//叶结点数
for (int i = 1; i <= q; i++)//当多边形退化为1(不算根结点那条边)条边时
{
t[i][i] = 0;
}
for (int len = 2; len <= q; len++)
{
for (int i = 1; i <= q - len + 1; i++)
{
int j = i + len - 1;
int min = 1000000;
int mid = 0;
for(int k = i; k < j; k++)
{
int temp = t[i][k] + t[k + 1][j] + Weight(v[i - 1], v[k], v[j]);
if (temp < min)
{
min = temp;
mid = k;
}
}
t[i][j] = min;
s[i][j] = mid;
}
}
}
//权函数
int Weight(int i, int k, int j)
{
return i*k*j;
}
//输出三角形
void TraceBack(int i, int j)
{
if (i != j)
{
cout << "(V" << i - 1;
cout << " , V" << s[i][j] << " , ";
cout << "V" << j<<")";
cout << endl;
TraceBack(i, s[i][j]);
TraceBack(s[i][j] + 1, j);
}
}
void print()
{
for (int i = 1; i < n; i++)
{
for (int j = 1; j < n; j++)
{
cout << setw(4) << t[i][j] << " ";
}
cout << endl;
}
cout << endl;
for (int i = 1; i < n; i++)
{
for (int j = 1; j < n; j++)
{
cout << setw(4) << s[i][j] << " ";
}
cout << endl;
}
cout << endl;
cout << "最小三角剖分为:" << endl;
TraceBack(1, n-1);
}
public:
vector<vector<int> > t;//子多边形Vi-1Vi...Vj
vector<vector<int> > s;//
vector<int> v;//多边形每个顶点值,作为权函数w的参数
int n;//多边形边数,边V0Vn作为根结点,其余每条边代表一个最小子问题,作为叶结点
};
Trianglation T;
int main()
{
T.MinWight();
T.print();
return 0;
}