# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
862291 | guagua0407 | Love Polygon (BOI18_polygon) | C++17 | 220 ms | 23204 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.
//#pragma GCC optimize("O3")
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pii pair<int,int>
#define f first
#define s second
#define all(x) x.begin(),x.end()
#define _ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
void setIO(string s) {
freopen((s + ".in").c_str(), "r", stdin);
freopen((s + ".out").c_str(), "w", stdout);
}
const int mxn=1e5+5;
map<string,int> mp;
vector<int> adj[mxn];
bool visited[mxn];
bool visited2[mxn];
int nxt[mxn];
bool is_cycle[mxn];
bool used[mxn];
int prv[mxn];
vector<int> tmp;
int dif;
void dfs(int v){
//cout<<v<<' ';
tmp.push_back(v);
visited[v]=true;
for(auto u:adj[v]){
if(is_cycle[u]) continue;
dfs(u);
if(!used[u] and !used[v]){
used[u]=true;
used[v]=true;
}
}
}
int main() {_
int n;
cin>>n;
if(n&1){
cout<<-1<<'\n';
return 0;
}
int cnt=0;
for(int i=0;i<n;i++){
string a,b;
cin>>a>>b;
if(!mp.count(a)) mp[a]=cnt++;
if(!mp.count(b)) mp[b]=cnt++;
nxt[mp[a]]=mp[b];
adj[mp[b]].push_back(mp[a]);
}
for(int i=0;i<n;i++){
if(visited[i]) continue;
vector<int> vec;
int cur=i;
while(!visited[cur]){
vec.push_back(cur);
visited[cur]=true;
cur=nxt[cur];
}
bool tf=true;
vector<int> cycle;
reverse(all(vec));
int rec=cur;
for(auto v:vec){
if(tf){
is_cycle[v]=true;
prv[rec]=v;
rec=v;
cycle.push_back(v);
}
if(v==cur){
tf=false;
}
}
for(auto v:cycle){
tmp.clear();
dfs(v);
//cout<<'\n';
}
int cur2=cur;
do{
if(used[cur]) break;
cur2=nxt[cur2];
}while(cur2!=cur);
int cur3=cur2;
vector<int> tmp2;
do{
if(used[cur3]){
for(auto v:tmp2){
used[v]=true;
}
if((int)tmp2.size()%2==1){
used[tmp2.back()]=false;
}
tmp2.clear();
}
else{
tmp2.push_back(cur3);
}
cur3=nxt[cur3];
}while(cur3!=cur2);
if((int)cycle.size()==2 and (int)tmp2.size()==2){
dif++;
}
for(auto v:tmp2){
used[v]=true;
}
if((int)tmp2.size()%2==1){
used[tmp2.back()]=false;
}
tmp2.clear();
}
int cnt2=0;
for(int i=0;i<n;i++){
//cout<<used[i]<<' ';
if(used[i]) cnt2++;
}
//cout<<'\n';
cout<<(cnt2/2+n-cnt2-dif)<<'\n';
return 0;
}
//maybe its multiset not set
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... |