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>
#include <math.h>
//in the name of god,aka allah
//**gray sety orz**
using namespace std;
#define pi pair<long long , long long>
#define pii pair<long long , pair<long long , long long>>
const int maxm = 5e5;
const long long mod = 1e9 + 7 ;
typedef long long ll;
ll l,r,mid;
ll n,m;
ll dis[maxm] , sum[maxm];
bool isval(int mid){
//cout << mid <<" " << mid*mid-mid <<endl;
if (((mid-1)*mid)/2 < m) return 0;
return 1;
}
ll darage[maxm] , ss , mm;
queue<int> q;
vector<pi> g[maxm] , z[maxm];
ll sath[maxm];
bool vis[maxm] , gos[maxm];
ll pedaret[maxm];
ll get_par(ll v){
if (pedaret[v]==v) return v;
return pedaret[v] = get_par(pedaret[v]);
}
void merge(ll r , ll q){
if (get_par(r)!=get_par(q))l+=max(darage[r],darage[q])*1ll*sath[r]*1ll*sath[q];
r = get_par(r) , q = get_par(q);
if (r!=q){
if (sath[r]<sath[q]) swap(r,q);
pedaret[q] = r;
sath[r] += sath[q];
}
return ;
}
ll pars1[maxm] , pars2[maxm];
vector<ll> se[maxm];
set<string> st;
ll rp[maxm];
pi w[maxm];
ll dp[maxm];
//ll rw[maxm][maxm];
map<string,ll> mp;
const int MM = 1e5+5;
int ind[MM],nxt[MM];
bool done[MM];
vector<int> adj[MM];
string back[MM];
int mx = 0;
int conv(string s){
if(mp.find(s) ==mp.end()) mp.insert({s,mp.size()}), back[mp.size()-1] = s; // 0-index
return mp[s];
}
int main() {
cin >> n;
if(n%2) return cout<<-1,0;
for(int i = 0; i < n; i++){
string a,b;
cin >> a >> b;
int aa = conv(a), bb = conv(b);
nxt[aa] = bb;
ind[bb]++;
}
for(int i = 0; i < n; i++) if(nxt[nxt[i]] == i && nxt[i] != i) done[i] = 1, done[nxt[i]] = 1;
queue<int> q;
for(int i = 0; i < n; i++) if(!done[i] && ind[i] == 0) q.push(i);
int ans = 0;
while(!q.empty())
{
int u = q.front(); q.pop();
//db(back[u])
ans++; done[u] = 1;
if(!done[nxt[u]])
{
if(--ind[nxt[nxt[u]]] == 0 && !done[nxt[nxt[u]]]) q.push(nxt[nxt[u]]);
//db(back[nxt[u]])
done[nxt[u]] = 1;
}
}
//db(done[conv("d")])
for(int i = 0; i < n; i++)
{
if(!done[i])
{
int len = 1;
done[i] = 1;
for(int pos = nxt[i]; pos != i; done[pos] = 1, pos = nxt[pos]) len++;
//db(len)
ans += (len+1)/2;
}
}
cout << ans << "\n";
}
# | 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... |