P5149 会议座位(逆序对)

看到本题有字典树就来了,结果直接map下,也可做。

思路1:map,然后上BIT。

思路2:字典树实现类map,然后上BIT。

code

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull; 
const int N=1e5+5,M=2e4+5,inf=0x3f3f3f3f,mod=1e9+7;
#define mst(a,b) memset(a,b,sizeof a)
#define PII pair<int,int>
#define fi first
#define se second
#define pb emplace_back
#define SZ(a) (int)a.size()
#define IOS ios::sync_with_stdio(false),cin.tie(0) 
void Print(int *a,int n){
	for(int i=1;i<n;i++)
		printf("%d ",a[i]);
	printf("%d\n",a[n]); 
}
#define lowbit(x) x&(-x)
ll s[N];
int n;
void upd(int x,int v){
	while(x<=n){
		s[x]+=v;x+=lowbit(x);
	}return;
}
ll que(int x){
	ll ans=0;
	while(x){
		ans+=s[x];x-=lowbit(x);
	}return ans;
}
unordered_map<string,int>mp;
string a[N];
void solve(){
	//think twice code once
	IOS;
	cin>>n;
	for(int i=1;i<=n;i++){
		string s;cin>>s;
		mp[s]=i;
	}
	for(int i=1;i<=n;i++) cin>>a[i];
	ll ans=0;
	for(int i=n;i;i--){
		int j=mp[a[i]];
		//printf("%d\n",j);
		ans+=que(j-1);
		upd(j,1);
	}
	printf("%lld\n",ans);
}
int main(){
	solve();
	return 0;
}
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull; 
const int N=5e5+5,M=2e4+5,inf=0x3f3f3f3f,mod=1e9+7;
#define mst(a,b) memset(a,b,sizeof a)
#define PII pair<int,int>
#define fi first
#define se second
#define pb emplace_back
#define SZ(a) (int)a.size()
#define IOS ios::sync_with_stdio(false),cin.tie(0) 
void Print(int *a,int n){
	for(int i=1;i<n;i++)
		printf("%d ",a[i]);
	printf("%d\n",a[n]); 
}
#define lowbit(x) x&(-x)
ll s[N];
int n;
void upd(int x,int v){
	while(x<=n){
		s[x]+=v;x+=lowbit(x);
	}return;
}
ll que(int x){
	ll ans=0;
	while(x){
		ans+=s[x];x-=lowbit(x);
	}return ans;
}
struct node{
	int son[80];
	int id;
}a[N];
int tot;
void ins(string s,int x){
	int p=0;
	for(int i=0;i<SZ(s);i++){
		if(!a[p].son[s[i]-'A']) a[p].son[s[i]-'A']=++tot;
		p=a[p].son[s[i]-'A']; 
	}
	a[p].id=x;
}
int get(string s){
	int p=0;
	for(int i=0;i<SZ(s);i++){
		p=a[p].son[s[i]-'A']; 
	}
	return a[p].id;
}
int b[N];
void solve(){
	//think twice code once
	IOS;
	cin>>n;
	for(int i=1;i<=n;i++){
		string s;cin>>s;
		ins(s,i);
	}
	for(int i=1;i<=n;i++){
		string s;
		cin>>s;
		b[i]=get(s);
	}
	ll ans=0;
	for(int i=1;i<=n;i++){
		upd(b[i],1);
		ans+=i-que(b[i]);
	}
	cout<<ans<<'\n';
}
int main(){
	solve();
	return 0;
}