您的位置:首页 > 其它

UVALive 6511 Term Project

2015-10-04 21:01 281 查看

Term Project

Time Limit: 3000ms
Memory Limit: 131072KB
This problem will be judged on UVALive. Original ID: 6511
64-bit integer IO format: %lld Java class name: Main

#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
struct arc{
int to,next;
arc(int x = 0,int y = -1){
to = x;
next = y;
}
}e[maxn*10];
int head[maxn],dfn[maxn],low[maxn],belong[maxn],cnt[maxn];
int tot,clk,scc;
bool instack[maxn];
stack<int>stk;
void init(){
for(int i = tot = clk = scc = 0; i < maxn; ++i){
head[i] = -1;
dfn[i] = 0;
cnt[i] = belong[i] = 0;
instack[i] = false;
}
while(!stk.empty()) stk.pop();
}
void add(int u,int v){
e[tot] = arc(v,head[u]);
head[u] = tot++;
}
void tarjan(int u){
dfn[u] = low[u] = ++clk;
instack[u] = true;
stk.push(u);
for(int i = head[u]; ~i; i = e[i].next){
if(!dfn[e[i].to]){
tarjan(e[i].to);
low[u] = min(low[u],low[e[i].to]);
}else if(instack[e[i].to]) low[u] = min(low[u],dfn[e[i].to]);
}
if(low[u] == dfn[u]){
scc++;
int v;
do{
instack[v = stk.top()] = false;
belong[v] = scc;
stk.pop();
cnt[scc]++;
}while(v != u);
}
}
int main(){
int kase,n;
scanf("%d",&kase);
while(kase--){
init();
scanf("%d",&n);
int ret = 0;
for(int i = 1,tmp; i <= n; ++i){
scanf("%d",&tmp);
add(i,tmp);
ret += i == tmp;
}
for(int i = 1; i <= n; ++i)
if(!dfn[i]) tarjan(i);
for(int i = 1; i <= scc; ++i)
if(cnt[i] > 1) ret += cnt[i];
printf("%d\n",n - ret);
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: