Codeforces1027D捉老鼠 图论 dfs

题目链接

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;
}

猜你喜欢

转载自blog.csdn.net/codetypeman/article/details/82153970
今日推荐