关闭

CF 4D Mysterious Present

333人阅读 评论(0) 收藏 举报

dfs题!!用Dp!可是就这么简单的思路,我偏偏绕远路,用LCS来DP求,被无情的MLE!

#include<iostream>
#include<cstring>
using namespace std;
int dfs(int);
int w[5001],h[5001],d[5001],p[5001],n;
main()
{
	cin>>n;
	for(int i=0;i<=n;i++)
	cin>>w[i]>>h[i];
	memset(d,0,sizeof(d));
	int k=dfs(0);
	cout<<k<<"\n";
	int i=0;
	while(p[i])
	{
		cout<<p[i]<<" ";
		i=p[i];
	}



	}
int dfs(int x)
{
	
	if(d[x])return d[x];
	for(int i=0;i<=n;i++)
	{
		if(w[i]>w[x] && h[i]>h[x])
		{
			int t=dfs(i);
			if(d[x]<t+1)
			{
				d[x]=t+1;
				p[x]=i;
			}
		}
	}
	return d[x];
}			

我的MLE代码~

#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
using namespace std;
struct Pair
{
    int v,id;
}w[5010],h[5010];
bool cmp(Pair a,Pair b)
{
    return a.v < b.v;
}
int  dp[5010][5010],ww[5010],hh[5010],r[5010][5010],cot[5010],k = 0;

bool a[1000010];
void print(int i,int j)
{
    if(i == 0||j == 0) return;
    if(r[i][j] == 3) {print(i-1,j-1);cot[k++] = ww[i];}
    else if(r[i][j] == 2) print(i-1,j);
    else print(i,j-1);
}
int main()
{
    //freopen("a.txt","r",stdin);
    int n,i,ans = 0,ii,jj,j,k1,k2;
    cin>>n>>w[0].v>>h[0].v;
    //int s[5010];
    memset(dp,0,sizeof(dp));
    w[0].id = 0;h[0].id = 0;
    for(i = 1;i <= n;i ++)
    {
        cin>>w[i].v >>h[i].v;
        w[i].id = h[i].id = i;
        //cout<<"dsa"<<endl;
    }
    sort(w,w + n+1,cmp);
    sort(h,h + n+1,cmp);
    k1 = 0;k2 = 0;
    memset(a,0,sizeof(a));
    //cout<<"dsa"<<endl;
    for(i = 0;i <= n;i ++)
    if(w[i].id == 0) break;
    while(i <= n) {if(a[w[i].v]==0){ww[k1++] = w[i].id;a[w[i].v] = 1;}i ++;}
    //cout<<k1<<k2<<endl;
    memset(a,0,sizeof(a));
    for(i = 0;i <= n;i ++)
    if(h[i].id == 0) break;
    while(i <= n) {if(a[h[i].v]==0){hh[k2++] = h[i].id;a[h[i].v] = 1;}i ++;}
    //cout<<k1<<k2<<endl;
    for(i = 0;i < 5010;i ++) {dp[i][0] = 0;dp[0][i] = 0;}
    for(i = 1;i < k1;i ++)
    {
        for(j = 1;j < k2;j ++)
        {
            if(ww[i] == hh[j]) {dp[i][j] = dp[i-1][j-1]+1;r[i][j] = 3;}
            else if(dp[i-1][j] >= dp[i][j-1]) {dp[i][j] = dp[i-1][j];r[i][j] = 2;}
            else {dp[i][j] = dp[i][j-1];r[i][j] = 1;}
        }
    }
    //cout<<k1<<k2<<endl;
    cout<<dp[k1-1][k2-1]<<endl;
    print(k1-1,k2-1);
    if(k > 0) cout<<cot[0];
    for(i = 1;i < k;i ++) cout<<" "<<cot[i];
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:72714次
    • 积分:1571
    • 等级:
    • 排名:千里之外
    • 原创:92篇
    • 转载:3篇
    • 译文:0篇
    • 评论:4条
    最新评论