LA 3716 DNA Regions (二分/排序)

本文介绍了一种在两条DNA链中寻找最长相似区段的算法,该算法通过维护一个单调递增栈并采用二分搜索或排序的方法来解决这一问题。适用于长度在150,000以内的DNA序列,能有效处理不超过99%的变异比例。

LA 3716 DNA Regions

题目大意:

给两条长度为n的DNA链A和B,找出一段最长的区间使得区间内的突变位置不超过p%.即找出尽可能长的区间,使得区间内有不超过p%x满足AxBx.
(1n150000,1p99).

题目分析:

设sum[i]表示到i位置为止对应字母不同的个数.
那么对应一个合法区间(l,r],须有

sum[r]sum[l]rlp100

100(sum[r]sum[l])p(rl)

sum[r]100rpsum[l]lp

K[i]=sum[i]100ip,则若K[i]K[j],存在(j,i]为合法区间.

解法一(二分):

维护一个K单调递增栈,在栈里进行二分查找.

解法一代码:

//二分
#include<cstdio>
#include<iostream>
#include<algorithm>

using namespace std;

const int maxn=150000+10;

char A[maxn],B[maxn];
int sum[maxn],st[maxn],n,p;

int binary_search(int top,int pos)//在单调栈st中,在[0,top]中找到最靠前大于等于pos的sum值对应编号 
{
    int L=0,R=top,ans=-1;//-1表示未找到 
    while(L<=R) {
        int mid=(L+R)>>1;
        if(sum[pos]<=sum[st[mid]]) ans=mid,R=mid-1;
        else L=mid+1;
    }
    return ans;
}

int main()
{
    while(scanf("%d%d",&n,&p)==2&&n) {
        scanf("%s%s",A+1,B+1);
        int cnt=0;
        for(int i=1;i<=n;i++) {
            if(A[i]!=B[i]) ++cnt;
            sum[i]=cnt*100-i*p;
        }
        int top=0,ans=0;st[0]=0;
        for(int i=1;i<=n;i++) {
            int pos=binary_search(top,i);
            if(pos>=0) ans=max(ans,i-st[pos]);
            if(sum[i]>sum[st[top]]) st[++top]=i;
            //若sum[i]<=sum[st[top]],对于后面的点来说,st[top]要比i更能形成合法解,且解比i更优 
        }
        if(ans) printf("%d\n",ans);
        else printf("No solution.\n");
    }
    return 0;
}

解法二(排序):

现将原序列以K值从大到小排序,那么后面的定比前面小,那么若后面的编号小于前面的,就可以形成合法解.

解法二代码:

#include<cstdio>
#include<iostream>
#include<algorithm>

using namespace std;

const int maxn=150000+10;

struct Node {
    int id,sum;
    bool operator < (const Node& rhs) const {
        return sum>rhs.sum||(sum==rhs.sum&&id<rhs.id);//注意sum相等时,id小的在前面 
    }
}N[maxn];

int n,p;
char A[maxn],B[maxn];

int main()
{
    while(scanf("%d%d",&n,&p)==2&&n) {
        scanf("%s%s",A+1,B+1);
        int cnt=0;
        N[0].sum=N[0].id=0;
        for(int i=1;i<=n;i++) {
            if(A[i]!=B[i]) ++cnt;
            N[i].sum=cnt*100-i*p;
            N[i].id=i;
        }
        sort(N,N+n+1);
        int id_min=N[0].id,ans=0;
        for(int i=1;i<=n;i++)
            if(N[i].id<id_min) id_min=N[i].id;//若当前编号比id_min小,更新id_min 
            else ans=max(ans,N[i].id-id_min);//若可以形成合法解,尝试更新答案  
        if(ans) printf("%d\n",ans);
        else printf("No solution.\n");
    }
    return 0;
}
### 回答问题 以下是 `Writer` 结构体的实现及其解释: ```rust /// Provides high-level interface over the sequence of memory regions /// defined by writable descriptors in the descriptor chain. /// /// Note that virtio spec requires driver to place any device-writable /// descriptors after any device-readable descriptors (2.6.4.2 in Virtio Spec v1.1). /// Writer will start iterating the descriptors from the first writable one and will /// assume that all following descriptors are writable. pub struct Writer { mem: GuestMemory, regions: DescriptorChainRegions, } ``` --- #### 1. **结构体定义** - `Writer` 是一个高级接口,用于操作描述符链中可写的内存区域。 - 根据 VirtIO 规范(VirtIO Spec v1.1 的第 2.6.4.2 节),驱动程序必须将设备可写描述符放在设备可读描述符之后。因此,`Writer` 假设从第一个可写描述符开始的所有描述符都是可写的。 --- #### 2. **字段解释** - **`mem: GuestMemory`**: - 表示虚拟机的内存映射对象。`GuestMemory` 是一个抽象类型,通常用于管理虚拟机的内存区域。 - 它允许访问和操作虚拟机的内存空间。 - **`regions: DescriptorChainRegions`**: - 表示描述符链中可写的内存区域序列。 - `DescriptorChainRegions` 是一个封装类型,存储了描述符链中所有可写区域的详细信息。 --- #### 3. **方法实现** ##### (1) **初始化 Writer** ```rust impl Writer { /// Creates a new Writer instance for the given descriptor chain. pub fn new(mem: GuestMemory, regions: DescriptorChainRegions) -> Self { Writer { mem, regions } } } ``` - **解释**: - `new` 方法用于创建一个新的 `Writer` 实例。 - 需要提供 `GuestMemory` 和 `DescriptorChainRegions` 参数。 --- ##### (2) **获取可写区域的总大小** ```rust impl Writer { /// Returns the total number of bytes available for writing. pub fn available_bytes(&self) -> usize { self.regions.iter().map(|region| region.len()).sum() } } ``` - **解释**: - `available_bytes` 方法返回描述符链中所有可写区域的总字节数。 - 使用 `regions.iter()` 遍历所有可写区域,并通过 `map` 和 `sum` 计算总大小。 --- ##### (3) **向描述符链中写入数据** ```rust impl Writer { /// Writes data into the descriptor chain. pub fn write_all(&mut self, buf: &[u8]) -> Result<usize, io::Error> { let mut bytes_written = 0; for region in self.regions.iter_mut() { let remaining = &buf[bytes_written..]; if remaining.is_empty() { break; } let region_len = std::cmp::min(remaining.len(), region.len()); self.mem.write_slice(&remaining[..region_len], region.addr())?; bytes_written += region_len; } Ok(bytes_written) } } ``` - **解释**: - `write_all` 方法将数据从缓冲区写入到描述符链的可写区域中。 - 遍历所有可写区域,逐个写入数据。 - 使用 `std::cmp::min` 确保不会超出当前区域的大小。 - 调用 `self.mem.write_slice` 将数据写入到虚拟机的内存中。 --- ##### (4) **检查是否还有可写区域** ```rust impl Writer { /// Returns true if there are no more writable regions. pub fn is_exhausted(&self) -> bool { self.regions.iter().all(|region| region.len() == 0) } } ``` - **解释**: - `is_exhausted` 方法检查是否还有可用的可写区域。 - 如果所有区域的大小为 0,则返回 `true`。 --- ### 示例代码 以下是一个完整的使用示例,展示如何操作 `Writer`: ```rust fn process_writer(writer: &mut Writer, data: &[u8]) -> Result<(), io::Error> { // Check if there are any writable regions if writer.is_exhausted() { println!("No writable regions available"); return Ok(()); } // Write data into the descriptor chain let bytes_written = writer.write_all(data)?; println!("Wrote {} bytes to the descriptor chain", bytes_written); Ok(()) } ``` - **解释**: - 首先检查是否有可用的可写区域。 - 如果有,则将数据写入到描述符链中。 --- ### 总结 `Writer` 是 VirtIO 协议中的一个重要组件,用于操作描述符链中可写的内存区域。它提供了简单易用的接口,隐藏了底层复杂的内存映射逻辑。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值