2021-9-21每日刷题打卡

一、POJ-1947:Rebuilding Roads

1.1 问题描述

The cows have reconstructed Farmer John’s farm, with its N barns (1 <= N <= 150, number 1…N) after the terrible earthquake last May. The cows didn’t have time to rebuild any extra roads, so now there is exactly one way to get from any given barn to any other barn. Thus, the farm transportation system can be represented as a tree.

Farmer John wants to know how much damage another earthquake could do. He wants to know the minimum number of roads whose destruction would isolate a subtree of exactly P (1 <= P <= N) barns from the rest of the barns.

题目大意:

给你一棵树,求最少剪掉几条边使能够得到一个p个节点的树。

1.2 问题解决

#include <iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
const int maxn=250;
const int INF=0x3f3f3f3f;
struct node
{
    int v;
    node *next;
} edge[maxn<<1],*head[maxn];
int n,m,cnt,dp[maxn][maxn];
void adde(int u,int v)
{
    edge[cnt].v=v;
    edge[cnt].next=head[u];
    head[u]=&edge[cnt++];
}
void dfs(int fa,int u)
{
    int i,j,v,mm=INF;
    node *p;
 
    dp[u][1]=0;
    for(p=head[u];p!=NULL;p=p->next)
    {
        v=p->v;
        if(v==fa)
            continue;
        dfs(u,v);
        for(i=m;i>=1;i--)
        {
            mm=dp[u][i]+1;
            for(j=1;j<i;j++)
                mm=min(mm,dp[u][j]+dp[v][i-j]);
            dp[u][i]=mm;
        }
    }
}
int main()
{
    int i,u,v,ans;
 
    while(~scanf("%d%d",&n,&m))
    {
        cnt=0;
        memset(head,0,sizeof head);
        memset(dp,0x3f,sizeof dp);
        for(i=1;i<n;i++)
        {
            scanf("%d%d",&u,&v);
            adde(u,v);
            adde(v,u);
        }
        dfs(1,1);
        ans=dp[1][m];
        for(i=1;i<=n;i++)
            ans=min(ans,dp[i][m]+1);
        printf("%d\n",ans);
    }
    return 0;
}

二、Leetcode-242:有效的字母异位词

2.1 问题描述

img

2.2 问题解决

class Solution {
    public boolean isAnagram(String s, String t) {
        int[] arr_s = new int[26];
        int[] arr_t = new int[26];

        if(s.length() != t.length()) return false;

        char[] s_copy = s.toCharArray();
        char[] t_copy = t.toCharArray();

        for(int i = 0; i < s.length(); i++)
        {
            arr_s[s_copy[i] - 'a']++;
            arr_t[t_copy[i] - 'a']++;
        }

        for(int i = 0; i < 26; i++)
            if(arr_s[i] != arr_t[i]) return false;
        
        return true;
    }
}

三、生词

barms n. 谷仓

isolate v. 隔离

四、参考文章

  1. Rebuilding Roads
  2. Rebuilding Roads–树形DP
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值