# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
837248 | 1075508020060209tc | Love Polygon (BOI18_polygon) | C++14 | 305 ms | 35540 KiB |
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
#define int long long
int n;
vector<int>e[200005];
vector<int>ee[200005];
int dgr[200005];
int alrd[200005];
int lve[200005];
int hs[200005];
void init(){
cin>>n;
int __id=0;
map<string,int>mp;
for(int i=1;i<=n;i++){
string s;
string t;
cin>>s>>t;
if(mp[s]==0){
mp[s]=++__id;
}
if(mp[t]==0){
mp[t]=++__id;
}
lve[mp[s]]=mp[t];
e[mp[s]].push_back(mp[t]);
// ee[mp[s]].push_back(mp[t]);
// ee[mp[t]].push_back(mp[s]);
dgr[mp[t]]++;
}
for(int i=1;i<=n;i++){
if(lve[i]!=i&&lve[lve[i]]==i){
alrd[i]=1;
hs[i]=1;
dgr[i]=0;
}
}
for(int i=1;i<=n;i++){
if(alrd[i]){continue;}
if(alrd[e[i][0]]){
e[i][0]=i;
lve[i]=i;
dgr[i]++;
}
}
if(n%2==1){
cout<<"-1";exit(0);
}
}
int vis[200005];
int dp[200005];
int ans;
void dfs(int nw,int pa){
vis[nw]=1;
for(int i=0;i<ee[nw].size();i++){
int v=ee[nw][i];
if(v==pa){continue;}
dfs(v,nw);
dp[nw]+=dp[v];
if(hs[v]==0&&hs[nw]==0){
hs[v]=1;hs[nw]=1;
dp[nw]++;
ans++;
}
}
}
int uf[200005];
int sz[200005];
int fin(int x){
if(uf[x]==x){return x;}
uf[x]=fin(uf[x]);
return uf[x];
}
void mrg(int a,int b){
int pa=fin(a);int pb=fin(b);
if(pa==pb){return;}
uf[pa]=pb;
sz[pb]+=sz[pa];
}
signed main() {
init();
ans=0;
queue<int>q;
for(int i=1;i<=n;i++){
if(hs[i]){continue;}
if(dgr[i]==0){
q.push(i);
}
}
while(q.size()){
int nw=q.front();
q.pop();
for(int i=0;i<e[nw].size();i++){
int v=e[nw][i];
dgr[v]--;
if(dgr[v]==0){
q.push(v);
}
ee[v].push_back(nw);
}
}
for(int i=1;i<=n;i++){
if(alrd[i]){continue;}
if(hs[i]){continue;}
if(dgr[i]==1){
dfs(i,0);
}
}
for(int i=1;i<=n;i++){
uf[i]=i;
sz[i]=1;
}
for(int i=1;i<=n;i++){
if(hs[i]){continue;}
if(hs[lve[i]]){continue;}
mrg(i,lve[i]);
}
for(int i=1;i<=n;i++){
if(hs[i]){continue;}
if(fin(i)==i){
ans+=(sz[fin(i)]+1)/2;
}
}
cout<<ans<<endl;
}
Compilation message (stderr)
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |