C. Equalize

C. Equalize

time limit per test

1 second

memory limit per test

256 megabytes

input

standard input

output

standard output

You are given two binary strings a

and b of the same length. You can perform the following two operations on the string a

:

  • Swap any two bits at indices i

and j respectively (1≤i,j≤n), the cost of this operation is |i−j|, that is, the absolute difference between i and j

  • .
  • Select any arbitrary index i
  • (1≤i≤n) and flip (change 0 to 1 or 1 to 0) the bit at this index. The cost of this operation is 1

    Find the minimum cost to make the string a

    equal to b. It is not allowed to modify string b

    .

    Input

    The first line contains a single integer n

    (1≤n≤106) — the length of the strings a and b

    .

    The second and third lines contain strings a

    and b

    respectively.

    Both strings a

    and b have length n

    and contain only '0' and '1'.

    Output

    Output the minimum cost to make the string a

    equal to b

    .

    Examples

    Input

    Copy

    3
    100
    001
    
    Output

    Copy

    2
    
    Input

    Copy

    4
    0101
    0011
    
    Output

    Copy

    1
    

    Note

    In the first example, one of the optimal solutions is to flip index 1

    and index 3, the string a changes in the following way: "100" → "000" → "001". The cost is 1+1=2

    .

    The other optimal solution is to swap bits and indices 1

    and 3, the string a changes then "100" → "001", the cost is also |1−3|=2

    .

    In the second example, the optimal solution is to swap bits at indices 2

    and 3, the string a changes as "0101" → "0011". The cost is |2−3|=1

    .


    题意:

            给你2串01字符串.,有2种操作,将i和j对调代价为abs(i-j)or将i位置的数0变1,1变0代价为1,让你计算出a串变b串的最小代价。

      思路:

               观察:串只有01,且只有2串,长度为1e6,所以只有O(n)的方法

               假设:据观察可得,若对调位置不是相邻,代价必定比反转2个位置高,即遍历字符串a并判相邻字符串能否对调即可

               验证:代码

               得出结论:假设正确

      code:

            

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<vector>
#include<queue>
#include<string>
#include<stack>
#include<string.h>
# include <cstdio>
# include <iostream>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <ostream>
#include <string>
#include <utility>
#include <vector>
using namespace std;
const int Max=1e6+5;
char s1[Max],s2[Max];
int book[Max];
int main()
{
	int n,ans;
	cin>>n;
	scanf("%s",s1);
	scanf("%s",s2);
	for(int i=0;i<n-1;i++)
	{
		if(book[i]||s1[i]==s2[i])
			continue;
		else
		{
			if(s1[i+1]!=s2[i+1]&&s1[i+1]!=s1[i])
			{
				book[i+1]=1;
			}
			ans++;
		}
	}
	if(s1[n-1]!=s2[n-1]&&!book[n-1])
		ans++;
	cout<<ans<<endl;
	return 0;
}

 

解释一下这个核心: class ImageNetPolicy(object): """ Randomly choose one of the best 24 Sub-policies on ImageNet. Example: >>> policy = ImageNetPolicy() >>> transformed = policy(image) Example as a PyTorch Transform: >>> transform=transforms.Compose([ >>> transforms.Resize(256), >>> ImageNetPolicy(), >>> transforms.ToTensor()]) """ def __init__(self, total_iter, fillcolor=(128, 128, 128)): self.total_iter = total_iter self.gamma = 0 self.policies = [ SubPolicy(0.4, "posterize", 8, 0.6, "rotate", 9, fillcolor), SubPolicy(0.6, "solarize", 5, 0.6, "autocontrast", 5, fillcolor), SubPolicy(0.8, "equalize", 8, 0.6, "equalize", 3, fillcolor), SubPolicy(0.6, "posterize", 7, 0.6, "posterize", 6, fillcolor), SubPolicy(0.4, "equalize", 7, 0.2, "solarize", 4, fillcolor), SubPolicy(0.4, "equalize", 4, 0.8, "rotate", 8, fillcolor), SubPolicy(0.6, "solarize", 3, 0.6, "equalize", 7, fillcolor), SubPolicy(0.8, "posterize", 5, 1.0, "equalize", 2, fillcolor), SubPolicy(0.2, "rotate", 3, 0.6, "solarize", 8, fillcolor), SubPolicy(0.6, "equalize", 8, 0.4, "posterize", 6, fillcolor), SubPolicy(0.8, "rotate", 8, 0.4, "color", 0, fillcolor), SubPolicy(0.4, "rotate", 9, 0.6, "equalize", 2, fillcolor), SubPolicy(0.0, "equalize", 7, 0.8, "equalize", 8, fillcolor), SubPolicy(0.6, "invert", 4, 1.0, "equalize", 8, fillcolor), SubPolicy(0.6, "color", 4, 1.0, "contrast", 8, fillcolor), SubPolicy(0.8, "rotate", 8, 1.0, "color", 2, fillcolor), SubPolicy(0.8, "color", 8, 0.8, "solarize", 7, fillcolor), SubPolicy(0.4, "sharpness", 7, 0.6, "invert", 8, fillcolor), SubPolicy(0.6, "shearX", 5, 1.0, "equalize", 9, fillcolor), SubPolicy(0.4, "color", 0, 0.6, "equalize", 3, fillcolor), SubPolicy(0.4, "equalize", 7, 0.2, "solarize", 4, fillcolor), SubPolicy(0.6, "solarize", 5, 0.6, "autocontrast", 5, fillcolor), SubPolicy(0.6, "invert", 4, 1.0, "equalize", 8, fillcolor), SubPolicy(0.6, "color", 4, 1.0, "contrast", 8, fillcolor), SubPolicy(0.8, "equalize", 8, 0.6, "equalize", 3, fillcolor), ] def __call__(self, img): if random.uniform(0, 1) > self.gamma: policy_idx = random.randint(0, len(self.policies) - 1) self.gamma = min(1.0, self.gamma + 1.0 / self.total_iter) return self.policies[policy_idx](img) else: return img def __repr__(self): return "AutoAugment ImageNet Policy" class SubPolicy(object): def __init__( self, p1, operation1, magnitude_idx1, p2, operation2, magnitude_idx2, fillcolor=(128, 128, 128), ): ranges = { "shearX": np.linspace(0, 0.3, 10), "shearY": np.linspace(0, 0.3, 10), "translateX": np.linspace(0, 150 / 331, 10), "translateY": np.linspace(0, 150 / 331, 10), "rotate": np.linspace(0, 30, 10), "color": np.linspace(0.0, 0.9, 10), "posterize": np.round(np.linspace(8, 4, 10), 0).astype(np.int), "solarize": np.linspace(256, 0, 10), "contrast": np.linspace(0.0, 0.9, 10), "sharpness": np.linspace(0.0, 0.9, 10), "brightness": np.linspace(0.0, 0.9, 10), "autocontrast": [0] * 10, "equalize": [0] * 10, "invert": [0] * 10, } # from https://stackoverflow.com/questions/5252170/specify-image-filling-color-when-rotating-in-python-with-pil-and-setting-expand # noqa def rotate_with_fill(img, magnitude): rot = img.convert("RGBA").rotate(magnitude) return Image.composite( rot, Image.new("RGBA", rot.size, (128,) * 4), rot ).convert(img.mode) func = { "shearX": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, magnitude * random.choice([-1, 1]), 0, 0, 1, 0), Image.BICUBIC, fillcolor=fillcolor, ), "shearY": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, 0, 0, magnitude * random.choice([-1, 1]), 1, 0), Image.BICUBIC, fillcolor=fillcolor, ), "translateX": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, 0, magnitude * img.size[0] * random.choice([-1, 1]), 0, 1, 0), fillcolor=fillcolor, ), "translateY": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, 0, 0, 0, 1, magnitude * img.size[1] * random.choice([-1, 1])), fillcolor=fillcolor, ), "rotate": lambda img, magnitude: rotate_with_fill(img, magnitude), "color": lambda img, magnitude: ImageEnhance.Color(img).enhance( 1 + magnitude * random.choice([-1, 1]) ), "posterize": lambda img, magnitude: ImageOps.posterize(img, magnitude), "solarize": lambda img, magnitude: ImageOps.solarize(img, magnitude), "contrast": lambda img, magnitude: ImageEnhance.Contrast(img).enhance( 1 + magnitude * random.choice([-1, 1]) ), "sharpness": lambda img, magnitude: ImageEnhance.Sharpness(img).enhance( 1 + magnitude * random.choice([-1, 1]) ), "brightness": lambda img, magnitude: ImageEnhance.Brightness(img).enhance( 1 + magnitude * random.choice([-1, 1]) ), "autocontrast": lambda img, magnitude: ImageOps.autocontrast(img), "equalize": lambda img, magnitude: ImageOps.equalize(img), "invert": lambda img, magnitude: ImageOps.invert(img), } self.p1 = p1 self.operation1 = func[operation1] self.magnitude1 = ranges[operation1][magnitude_idx1] self.p2 = p2 self.operation2 = func[operation2] self.magnitude2 = ranges[operation2][magnitude_idx2] def __call__(self, img): if random.random() < self.p1: img = self.operation1(img, self.magnitude1) if random.random() < self.p2: img = self.operation2(img, self.magnitude2) return img
最新发布
10-23
import os import numpy as np import matplotlib.pyplot as plt import SimpleITK as sitk from skimage import segmentation, morphology, measure, filters, exposure def load_mhd_file(file_path): """加载.mhd文件并返回numpy数组""" image = sitk.ReadImage(file_path) array = sitk.GetArrayFromImage(image) return array def preprocess_ct(ct_slice): """CT图像预处理(归一化+直方图均衡化)""" # 限制HU值范围(-1000到400) ct_slice = np.clip(ct_slice, -1000, 400) # 归一化到0-255 ct_normalized = ((ct_slice - (-1000)) / (400 - (-1000)) * 255).astype(np.uint8) # 直方图均衡化增强对比度 return exposure.equalize_hist(ct_normalized) def lung_segmentation(ct_slice): """肺部区域分割算法""" # 1. 大津阈值法(Otsu)进行初始分割 thresh = filters.threshold_otsu(ct_slice) binary = ct_slice > thresh # 2. 形态学开运算去除小噪声 cleaned = morphology.opening(binary, morphology.disk(2)) # 3. 填充孔洞 filled = morphology.remove_small_holes(cleaned, area_threshold=300) # 4. 连通区域分析,保留最大两个区域(左右肺) label_image = measure.label(filled) regions = measure.regionprops(label_image) areas = [r.area for r in regions] if len(areas) > 0: # 按面积降序排序 areas_sorted = sorted(areas, reverse=True) # 保留前两个最大区域 mask = np.zeros_like(binary) for region in regions: if region.area in areas_sorted[:2]: mask |= label_image == region.label return mask return filled def main(): # 文件路径设置(修改为实际路径) ct_dir = "path/to/CT_folder" mask_dir = "path/to/Mask_folder" sample_file = "case_001.mhd" # 示例文件名 # 加载CT和Mask数据 ct_array = load_mhd_file(os.path.join(ct_dir, sample_file)) mask_array = load_mhd_file(os.path.join(mask_dir, sample_file)) # 选择中间切片进行处理 slice_idx = ct_array.shape[0] // 2 ct_slice = ct_array[slice_idx] true_mask = mask_array[slice_idx] # CT图像预处理 processed_ct = preprocess_ct(ct_slice) # 执行分割算法 pred_mask = lung_segmentation(processed_ct) # 结果可视化 plt.figure(figsize=(15, 10)) plt.subplot(1, 3, 1) plt.imshow(processed_ct, cmap='gray') plt.title('Original CT Slice') plt.axis('off') plt.subplot(1, 3, 2) plt.imshow(true_mask, cmap='gray') plt.title('Ground Truth Mask') plt.axis('off') plt.subplot(1, 3, 3) plt.imshow(pred_mask, cmap='gray') plt.title('Segmentation Result') plt.axis('off') plt.tight_layout() plt.savefig('lung_segmentation_results.png', dpi=300) plt.show() if __name__ == "__main__": main() 这个最终只能显示一个图像,我想显示文件夹中所有组数据最终显示的图像
07-04
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值