Codeforces1027D捉老鼠 图论 dfs

博客围绕女寝抓鼠问题展开,女寝有一只老鼠在各房间跑动,在不同房间设陷阱有不同花费。为保证抓住老鼠,需计算设陷阱的最小总花费。因老鼠路线成环,只需在环上找最小花费,且题中可能存在多个环。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

D. Mouse Hunt

Medicine faculty of Berland State University has just finished their admission campaign. As usual, about 80%80% of applicants are girls and majority of them are going to live in the university dormitory for the next 4 (hopefully) years.

The dormitory consists of nn rooms and a single mouse! Girls decided to set mouse traps in some rooms to get rid of the horrible monster. Setting a trap in room number i costs cici burles. Rooms are numbered from 1 to n.

Mouse doesn't sit in place all the time, it constantly runs. If it is in room ii in second tt then it will run to room aiai in second t+1 without visiting any other rooms inbetween (i=ai means that mouse won't leave room i). It's second 0 in the start. If the mouse is in some room with a mouse trap in it, then the mouse get caught into this trap.

That would have been so easy if the girls actually knew where the mouse at. Unfortunately, that's not the case, mouse can be in any room from 1 to n at second 0.

What it the minimal total amount of burles girls can spend to set the traps in order to guarantee that the mouse will eventually be caught no matter the room it started from?

Input

The first line contains as single integers n(1≤n≤2*10^5) — the number of rooms in the dormitory.

The second line contains nn integers c1,c2,…,cn (1≤ci≤10^4) — cici is the cost of setting the trap in room number ii.

The third line contains nn integers a1,a2,…,an(1≤ai≤n) — ai is the room the mouse will run to the next second after being in room i

题意:女寝有一只老鼠,一直各个房间里跑,从 i 跑到a [ i ];在每个房间放笼子的代价c [ i ] ,为了保证一定抓住这只老鼠,求放笼子的最小代价;

老鼠一直在跑,说明,他的路线一定成环,要抓住这只老鼠只需要在环上找最小的花费即可;这个题可能有多个环;

#include<iostream>
#include<vector>
#include<set>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
typedef long long LL;
const int MOD=1e9+7;
const int maxn=2e5+7;
const int INF=2e9;
int a[maxn];
int c[maxn];
int vis[maxn];
int tag[maxn];
int dfs(int rt)
{
    if(tag[rt]) return INF;
    vis[rt]++;
    int next=a[rt];
    int res=INF;
    if(vis[rt]==2)
    {
        res=min(c[rt],res);
        for(int i=next;i!=rt;i=a[i])
        {
            res=min(c[i],res);
        }
        return res;
    }
    res=min(res,dfs(next));
    tag[rt]=1;///搜索完之后标记为访问
    return res;
}
int main()
{
    int n;
    cin>>n;
    for(int i=1;i<=n;++i)
        scanf("%d",c+i);
    for(int i=1;i<=n;++i)
        scanf("%d",a+i);
    int ans=0;
    for(int i=1;i<=n;++i)
    {
        int t=dfs(i);
        if(t!=INF) ans+=t;
    }
    cout<<ans<<endl;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值