Problem Description
A rectangular polygon is a polygon whose edges are all parallel to the coordinate axes. The polygon must have a single,
non-intersecting boundary. No two adjacent sides must be parallel.
Johnny has several sticks of various lengths. He would like to construct a rectangular polygon. He is planning to use sticks as
horizontal edges of the polygon, and draw vertical edges with a pen.
Now Johnny wonders, how many sticks he can use. Help him, find the maximal number of sticks that Johnny can use. He will use sticks
only as horizontal edges. Input
The first line of the input file contains n — the number of sticks (1 ≤ n ≤ 100). The second line contains n integer numbers — the
lengths of the sticks he has. The length of each stick doesn’t exceed
200. Output
Print l — the number of sticks Johnny can use at the first line of the output file. The following 2l lines must contain the vertices
of the rectangular polygon Johnny can construct. Vertices must be
listed in order of traversal. The first two vertices must be the ends
of a horizontal edge. If there are several solution, output any one.
Vertex coordinates must not exceed 109 . If no polygon can be
constructed, output l = 0.
因为竖边可以随便加,所以问题就转化成从一些数中选出若干个组成两个集合,使两个集合的和相等,并使元素总数最大。
动态规划。dp[i][j]表示前i根木棍,上边比下边长j的最大元素总数。那么这根木棍可以不放,可以放在上面,可以放在下面。不难写出状态转移方程。
dp[i][j]=min{dp[i-1][j],dp[i-1][j+a[i]],dp[i-1][j-a[i]}。
因为下标可能为负,所以需要平移。
要输出方案,所以要记录路径。记录这根木棍干了什么即可。
输出的时候比较麻烦,注意题目的要求。
#include<cstdio>
#include<cstring>
int t(int x)
{
return x+20010;
}
int dp[110][50010],len[110],pa[110][50010],cnt1,cnt2;
//1:up 2:down
struct node
{
int x,y;
}a1[310],a2[310];
void add1(int x,int y)
{
cnt1++;
a1[cnt1].x=x;
a1[cnt1].y=y;
}
void add2(int x,int y)
{
cnt2++;
a2[cnt2].x=x;
a2[cnt2].y=y;
}
void prt(node p)
{
printf("%d %d\n",p.x,p.y);
}
int main()
{
int i,j,k,m,n,p,q,x,y,z,y1,y2,x1,x2;
while (scanf("%d",&n)==1)
{
for (i=1;i<=n;i++)
scanf("%d",&len[i]);
memset(dp,128,sizeof(dp));
dp[0][t(0)]=0;
memset(pa,0,sizeof(pa));
for (i=1;i<=n;i++)
for (j=-20000;j<=20000;j++)
{
dp[i][t(j)]=dp[i-1][t(j)];
if (dp[i-1][t(j-len[i])]+1>dp[i][t(j)])
{
dp[i][t(j)]=dp[i-1][t(j-len[i])]+1;
pa[i][t(j)]=1;
}
if (dp[i-1][t(j+len[i])]+1>dp[i][t(j)])
{
dp[i][t(j)]=dp[i-1][t(j+len[i])]+1;
pa[i][t(j)]=2;
}
}
printf("%d\n",dp[n][t(0)]);
cnt1=cnt2=0;
if (dp[n][t(0)])
{
y1=1;
y2=0;
x1=x2=0;
p=0;
for (i=n;i>=1;i--)
{
if (!pa[i][t(p)]) continue;
if (pa[i][t(p)]==1)
{
p-=len[i];
y1++;
add1(x1,y1);
x1+=len[i];
add1(x1,y1);
}
else
{
p+=len[i];
y2--;
add2(x2,y2);
x2+=len[i];
add2(x2,y2);
}
}
for (i=1;i<=cnt1;i++)
prt(a1[i]);
for (i=cnt2;i>=1;i--)
prt(a2[i]);
}
}
}