105282024-04-04 17:22:46111Kutyavetélkedő 2cpp17Runtime error 21/1001.222s2094820 KiB
#include<bits/stdc++.h>
using namespace std;

#define int long long

void scc_dfs(const auto&g,auto&v,auto&s,int i){
	if(v[i]){
		return;
	}
	v[i]=1;
	for(int j:g[i]){
		scc_dfs(g,v,s,j);
	}
	s.push_back(i);
}

int scc(const auto&g,const auto&gg,auto&c){
	int n=g.size();
	vector<int>v,s;
	v.assign(n,0);
	for(int i=0;i<n;i++){
		scc_dfs(g,v,s,i);
	}
	v.assign(n,0);
	for(int i=n-1;i>=0;i--){
		if(v[s[i]]){
			continue;
		}
		c.emplace_back();
		scc_dfs(gg,v,c.back(),s[i]);
	}
	return c.size();
}

signed main(){
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	int N,K;
	cin>>N>>K;
	vector<int>v(N);
	for(int i=0;i<N;i++){
		cin>>v[i];
	}
	int M;
	cin>>M;
	vector<vector<int>>g(K+1),gg(K+1);
	for(int i=0;i<M;i++){
		int a,b;
		cin>>a>>b;
		g[a].push_back(b);
		gg[b].push_back(a);
	}
	vector<vector<int>>c;
	int O=scc(g,gg,c);
	vector<int>cc(K+1);
	for(int i=0;i<O;i++){
		for(int j:c[i]){
			cc[j]=i;
		}
	}
	vector<vector<int>>h(O);
	for(int i=0;i<O;i++){
		for(int j:c[i]){
			for(int k:g[j]){
				int l=cc[k];
				if(l!=i){
					h[i].push_back(l);
				}
			}
		}
	}
	for(int i=0;i<O;i++){
		h[i].erase(unique(h[i].begin(),h[i].end()),h[i].end());
	}
	vector<int>w(O);
	vector<bitset<250001>>s(O);
	auto dfs=[&](auto self,int i)->void{
		if(w[i]){
			return;
		}
		w[i]=1;
		s[i][i]=1;
		for(int j:h[i]){
			self(self,j);
			s[i]|=s[j];
		}
	};
	for(int i=0;i<O;i++){
		dfs(dfs,i);
	}
	for(int i=1;i<=K;i++){
		sort(g[i].begin(),g[i].end());
	}
	int ans=2;
	for(int i=0;i+1<N;i++){
		if(binary_search(g[v[i]].begin(),g[v[i]].end(),v[i+1])){
			ans+=2;
			continue;
		}
		if(!s[cc[v[i]]][cc[v[i+1]]]){
			break;
		}
		ans+=1;
	}
	cout<<ans<<'\n';
	return 0;
}
SubtaskSumTestVerdictTimeMemory
subtask10/0
1Accepted3ms2080 KiB
2Accepted3ms2268 KiB
subtask221/21
3Accepted4ms8116 KiB
4Accepted4ms8292 KiB
5Accepted4ms7452 KiB
6Accepted6ms9828 KiB
7Accepted6ms10196 KiB
8Accepted6ms10184 KiB
9Accepted6ms10144 KiB
subtask30/45
10Accepted717ms505252 KiB
11Accepted578ms505432 KiB
12Runtime error801ms2094820 KiB
13Runtime error968ms2094600 KiB
14Runtime error787ms2094568 KiB
15Runtime error787ms2094564 KiB
16Runtime error808ms2094544 KiB
17Runtime error814ms2094536 KiB
18Runtime error813ms2094312 KiB
19Runtime error805ms2094312 KiB
20Runtime error1.001s2094084 KiB
subtask40/34
21Runtime error904ms2094088 KiB
22Runtime error1.172s2093860 KiB
23Time limit exceeded1.222s2093624 KiB
24Time limit exceeded1.213s2093400 KiB
25Time limit exceeded1.207s2093404 KiB
26Runtime error1.174s2093180 KiB