区间DP——Kattis - runningroutes

Kattis - runningroutes

The administrators at Polygonal School want to increase enrollment, but they are unsure if their gym can support having more students. Unlike a normal, boring, rectangular gym, the gym floor at Polygonal is a regular n-sided polygon! They affectionately refer to the polygon as P.

The coach has drawn several running paths on the floor of the gym. Each running path is a straight line segment connecting two distinct vertices of P. During gym class, the coach assigns each student a different running path, and the student then runs back and forth along their assigned path throughout the class period. The coach does not want students to collide, so each student’s path must not intersect any other student’s path. Two paths intersect if they share a common point (including an endpoint).

Given a description of the running paths in P, compute the maximum number of students that can run in gym class simultaneously.
Figure 1: Illustrations of the two sample inputs, with possible solutions highlighted in thick red lines. Solid black lines represent running paths that are not assigned to a student, and dashed black lines are used to show the boundary of P in places where no running path exists.
Input
The first line contains an integer n (3≤n≤500), the number of vertices in P. (The vertices are numbered in increasing order around P.) Then follows n lines of n integers each, representing a n×n symmetric binary matrix which we’ll call M. The jth integer on the ith line Mij is 1 if a running path exists between vertices i and j of the polygon, and 0 otherwise. It is guaranteed that for all 1≤i,j≤n, Mij=Mji and Mii=0.

Output
Print the maximum number of students that can be assigned to run simultaneously on the running paths, given the above constraints.

题解:

这道题很明显看起来是一个区间dp,为了避免破环成直过后存在重选的情况,我们这里的方程定义为
f ( i , j ) = f ( i + 1 , k 1 ) + f ( k + 1 , j ) + m a z e ( i , k ) f(i,j)=f(i+1,k-1)+f(k+1,j)+maze(i,k) 这样一个点就能保证只被一条线所使用了。然后就是区间dp的套路,枚举长度左右端点了。

#include <bits/stdc++.h>
using namespace std;
const int N=505;
int f[N][N];
int maze[N][N];
int main()
{
    int n; cin>>n;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            cin>>maze[i][j];
        }
    }
    for(int i=1;i<n;i++) f[i][i+1]=maze[i][i+1];
    for(int len=3;len<=n;len++){
        for(int l=1;l+len-1<=n;l++){
            int r=l+len-1;
            for(int k=l;k<=r;k++){
                f[l][r]=max(f[l][r],f[l+1][k-1]+f[k+1][r]+maze[l][k]);
            }
        }
    }
    cout<<f[1][n]<<endl;
}
发布了181 篇原创文章 · 获赞 10 · 访问量 5065

猜你喜欢

转载自blog.csdn.net/weixin_42979819/article/details/104217084