# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
940034 | 8pete8 | Love Polygon (BOI18_polygon) | C++17 | 259 ms | 13652 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<iostream>
#include<stack>
#include<map>
#include<vector>
#include<string>
#include<unordered_map>
#include <queue>
#include<cstring>
#include<limits.h>
#include <cassert>
#include<cmath>
#include<set>
#include<algorithm>
#include <iomanip>
#include<numeric> //gcd(a,b)
#include<bitset>
using namespace std;
#define ll long long
#define f first
#define endl "\n"
#define s second
#define pii pair<int,int>
#define ppii pair<int,pii>
#define vi vector<int>
#define pb push_back
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
#define F(n) for(int i=0;i<n;i++)
#define lb lower_bound
#define ub upper_bound
#define fastio ios::sync_with_stdio(false);cin.tie(NULL);
#pragma GCC optimize ("03,unroll-loops")
using namespace std;
#define int long long
#define double long double
const int mod=1e9+7,mxn=1e5+5,lg=30,inf=1e18,minf=-1e18;
void setIO(string name){
ios_base::sync_with_stdio(0); cin.tie(0);
freopen((name+".in").c_str(),"r",stdin);
freopen((name+".out").c_str(),"w",stdout);
}
map<string,int>id;
int t=1;
void put(string a){if(id[a]==0)id[a]=t++;}
int nxt[mxn+10],deg[mxn+10],paired[mxn+10];
bool vis[mxn+10];
int cnt=0;
void dfs(int cur){
cnt++;
vis[cur]=1;
if(!vis[nxt[cur]])dfs(nxt[cur]);
}
int32_t main(){
int n;cin>>n;
if(n%2){
cout<<-1;
return 0;
}
for(int i=0;i<n;i++){
string a,b;cin>>a>>b;
put(a);
put(b);
nxt[id[a]]=id[b];
if(nxt[id[b]]==id[a]&&id[a]!=id[b]){
paired[id[b]]=1;
paired[id[a]]=1;
}
//cout<<id[a]<<" "<<id[b]<<'\n';
deg[id[b]]++;
}
queue<int>q;//with 0 indeg
for(int i=1;i<=n;i++)if(!deg[i])q.push(i);
int ans=0;
while(!q.empty()){
int cur=q.front();
q.pop();
if(paired[nxt[cur]]||paired[cur]){
nxt[cur]=cur;
continue;
}
paired[nxt[cur]]=1;
paired[cur]=1;
//cout<<cur<<" "<<nxt[cur]<<'\n';
deg[nxt[nxt[cur]]]--;
if(deg[nxt[nxt[cur]]]==0&&!paired[nxt[nxt[cur]]])q.push(nxt[nxt[cur]]);
ans++;
}
for(int i=1;i<=n;i++)if(!paired[i]&&!vis[i]){
cnt=0;
dfs(i);
ans+=(cnt/2);
ans+=(cnt%2);
}
cout<<ans;
}
/*
considering 1 component
we can take the node with no indegree(no likes him :()
then forced the person he likes to likes him back then subtract degree
cost will be 1
we will be left with k people without a pair
then the cost will be 2*k;
*/
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... |