Codeforces 848A. From Y to Y (思维,构造)

本文介绍了一种字符串合并算法,该算法旨在寻找合并字符串时的最小代价。通过对相同字母合并的代价进行分析,并利用贪心策略,实现了有效的构造算法。
  • Source

  • Problem

    给定一个字符串,看作是n个长度为1的字符串,通过n-1次合并操作可变为一个长度为1的字符串,每次合并 s1,s2 s 1 , s 2 的代价为 zc=af(s1,c)f(s2,c) ∑ c = ′ a ′ ′ z ′ f ( s 1 , c ) ∗ f ( s 2 , c ) , c c s1,s2都出现的字符, f(s,c) f ( s , c ) c c s中出现的次数。每个问题都存在一个最小代价。
    给出一个最小代价,输出一个字符串满足此最小代价。

  • Solution

    不同字母的合并的代价为 0 0 ,只需要关注相同字母合并的代价。设目标字符串含有n a a ,可以找到这个规律:
    合并这n a a 的代价f(n)=n(n+1)2。用数组把 f(n) f ( n ) 存起来,然后用贪心构造即可。

  • Code

#include <bits/stdc++.h>
using namespace std;

int main()
{
    int a[500],k;
    int ans[30],p=0;
    for(int i=0;i<500;++i)
        a[i]=i*(i-1)/2;
    scanf("%d",&k);
    if(!k) {printf("iloveacm\n");return 0;}
    for(int i=490;k;--i)
    {
        while(a[i]<=k)
        {
            k-=a[i];
            ans[p++]=i;
        }
    }
    for(int i=0;i<p;++i)
    {
        char c='a'+i;
        for(int j=0;j<ans[i];++j)
            printf("%c",c);
    }
    printf("\n");
    return 0;
}
You are given a positive integer N and two strings S and T, each of length N and consisting of lowercase English letters. Determine whether it is possible to make S identical to T by repeating the operation below any number of times (possibly zero). If it is possible, also find the minimum number of operations required. Choose two lowercase English letters x,y and replace every occurrence of x in S with y. Constraints 1≤N≤2×10 5 N is an integer. Each of S and T is a string of length N, consisting of lowercase English letters. Input The input is given from Standard Input in the following format: N S T Output If it is possible to make S identical to T, print the minimum number of operations required. Otherwise, print −1. Sample Input 1 Copy 6 afbfda bkckbb Sample Output 1 Copy 4 By performing the operation four times in the following way, you can make S identical to T: Choose x= b and y= c. S becomes afcfda. Choose x= a and y= b. S becomes bfcfdb. Choose x= f and y= k. S becomes bkckdb. Choose x= d and y= b. S becomes bkckbb, which is identical to T. It cannot be done with fewer than four operations, so the minimum number of operations required is 4. Sample Input 2 Copy 4 abac abac Sample Output 2 Copy 0 S and T are already identical, so no operations are required. Sample Input 3 Copy 4 abac abrc Sample Output 3 Copy -1 No matter how you repeat the operation, it is impossible to make S identical to T. Sample Input 4 Copy 4 abac bcba Sample Output 4 Copy 4 C++,中文!!!
最新发布
03-30
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值