105272024-04-04 17:20:08111Kutyavetélkedő 2cpp17Time limit exceeded 21/1001.319s664952 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<set<int>>s(O);
	auto dfs=[&](auto self,int i)->void{
		if(w[i]){
			return;
		}
		w[i]=1;
		for(int j:h[i]){
			self(self,j);
			s[i].insert(s[j].begin(),s[j].end());
		}
		s[i].insert(i);
	};
	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]]].count(cc[v[i+1]])){
			break;
		}
		ans+=1;
	}
	cout<<ans<<'\n';
	return 0;
}
SubtaskSumTestVerdictTimeMemory
subtask10/0
1Accepted3ms1728 KiB
2Accepted3ms1932 KiB
subtask221/21
3Accepted3ms2432 KiB
4Accepted3ms2516 KiB
5Accepted3ms2828 KiB
6Accepted4ms3300 KiB
7Accepted4ms3304 KiB
8Accepted3ms3216 KiB
9Accepted4ms3512 KiB
subtask30/45
10Time limit exceeded1.315s214936 KiB
11Time limit exceeded1.258s208408 KiB
12Time limit exceeded1.296s558776 KiB
13Time limit exceeded1.307s618784 KiB
14Time limit exceeded1.304s558384 KiB
15Time limit exceeded1.299s559708 KiB
16Time limit exceeded1.287s631732 KiB
17Time limit exceeded1.299s598276 KiB
18Time limit exceeded1.294s664952 KiB
19Time limit exceeded1.294s601524 KiB
20Time limit exceeded1.312s609180 KiB
subtask40/34
21Time limit exceeded1.305s529784 KiB
22Time limit exceeded1.297s606412 KiB
23Time limit exceeded1.309s530424 KiB
24Time limit exceeded1.319s551720 KiB
25Time limit exceeded1.289s603956 KiB
26Time limit exceeded1.312s530736 KiB