Educational Codeforces Round 49 (Rated for Div. 2)-D. Mouse Hunt
程序员文章站
2022-06-04 08:14:30
...
思路:此题为一个图,由样例不难推出对于最小花费应该是每个树的根节点值和环的最小节点值,因此对于树的根节点可以用并查集来求得,而对于环,可以先用拓扑排序将环找出来,在DFS查找环的最小节点值即可
Code :
#include<iostream>
#include<vector>
#include<stack>
using namespace std;
const int MAX_N=200005;
int n;
int a[MAX_N];
int In[MAX_N];
int id[MAX_N];
bool boo[MAX_N];
vector<int> e[MAX_N];
stack<int> sta;
int Find(int x);
void tpSort(void);
int DFS(int k,int pp);
int main()
{
ios::sync_with_stdio(false);
cin>>n;
for(int i=1;i<=n;id[i]=i,++i)
cin>>a[i];
for(int i=1,x;i<=n;++i)
{
cin>>x;
e[i].push_back(x);
In[x]++;
id[Find(i)]=Find(x);
}
for(int i=1;i<=n;++i)
if(!In[i]) sta.push(i);
tpSort();
int ans=0;
for(int i=1;i<=n;++i)
{
if(boo[Find(i)]==true){
ans+=a[id[i]]; a[id[i]]=0;
}else ans+=DFS(id[i],id[i]);
}
cout<<ans<<endl;
return 0;
}
int Find(int x)
{
if(id[x]!=x) id[x]=Find(id[x]);
return id[x];
}
void tpSort(void)
{
while(!sta.empty()){
int u=sta.top(); sta.pop();
boo[u]=true;
for(auto t:e[u])
if(!(--In[t])) sta.push(t);
}
}
int DFS(int k,int pp)
{
int ans=a[k];
a[k]=0; boo[k]=true;
for(auto c:e[k])
if(c!=pp){
ans=min(ans,DFS(c,pp));
}
return ans;
}
上一篇: Educational Codeforces Round 85 (Rated for Div. 2) E - Divisor Paths
下一篇: Educational Codeforces Round 39 (Rated for Div. 2) D. Timetable - dp分组背包
推荐阅读
-
Educational Codeforces Round 71 (Rated for Div. 2)E. XOR Guessing
-
Educational Codeforces Round 97 (Rated for Div. 2) D. Minimal Height Tree
-
Educational Codeforces Round 60 (Rated for Div. 2) ----A - Best Subsegment(思维题)
-
Educational Codeforces Round 85 (Rated for Div. 2) C. Circle of Monsters(前缀和 预处理 贪心)
-
Educational Codeforces Round 98 (Rated for Div. 2) A-E 题解
-
Educational Codeforces Round 93 (Rated for Div. 2) A. Bad Triangle
-
Educational Codeforces Round 93 (Rated for Div. 2) B - Substring Removal Game
-
Educational Codeforces Round 99 (Rated for Div. 2) C. Ping-pong
-
第十五次训练:Educational Codeforces Round 72 (Rated for Div. 2) && Codeforces Round #582 (Div. 3)
-
第二次训练:Educational Codeforces Round 77 (Rated for Div. 2)