链接:
http://codeforces.com/contest/1141/problem/D
题意:
给定 n n n,及两个长度为 n n n的字符串 s s s, t t t;其中只含有26个小写字母和 ′ ? ′ '?' ′?′;分别来自 s s s, t t t字符串的两个相同的字符能够凑成一对,’?'能和出现的27种字符凑成一对,问最多凑成多少对,并输出所有的配对的 S S S i i i与 T T T j j j,若有多种方案,输出任何一种;
分析:
将27个字符,出现的位置分别放到各自对应的桶中,对于每一种x字符,首先应该将s中这个字符出现的位置与在t中出现的位置拿出来放到一个专门放置配对的桶里,这样就能保证s和t中至少有一个字符串的x被全部配对完,如果s剩下x字符,就拿出一个x在s中出现的位置,再去t中拿出一个’?‘出现的位置,然后放到配对的桶里,直至将x筛完,或者没有’?‘和x配对结束;如果t剩下x字符,同理;这样就能将26种字符筛选完毕,然后对于最后,如果有剩,要么剩下的是s中与t中不能配对的字符,剩下的就只有可能是s中的’?‘和t中的’?’,然后再分别各从s和t中取’?'放到配对的桶里,就可以了;
代码:
#include<algorithm>
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<vector>
#include<queue>
#include<stack>
#include<cmath>
#include<set>
#include<map>
using namespace std;
const int inf=0x7f7f7f7f;
const int maxn=1e1+50;
const int N=2e6+50;
typedef long long ll;
typedef struct{
ll u,v,next,w;
}Edge;
Edge e[N];
int cnt,head[N];
inline void add(int u,int v){
e[cnt].u=u;
e[cnt].v=v;
//e[cnt].w=w;
// e[cnt].f=f;
e[cnt].next=head[u];
head[u]=cnt++;
// e[cnt].u=v;
// e[cnt].v=u;
// e[cnt].w=0;
// e[cnt].f=-f;
// e[cnt].next=head[v];
// head[v]=cnt++;
}
inline void write(int x)
{
if(x<0)
putchar('-'),x=-x;
if(x>9)
write(x/10);
putchar(x%10+'0');
}
inline int read()
{
int x = 0;
int f = 1;
char c = getchar();
while (c<'0' || c>'9'){
if (c == '-')
f = -1;
c = getchar();
}
while (c >= '0'&&c <= '9'){
x = x * 10 + c - '0';
c = getchar();
}
return x*f;
}
int n,cot,a[N],b[N],ct1,ct2,mark[N];
string l,r;
stack<int>s1[256],s2[256];
vector<pair<int,int > >vec;
int main() {
cin>>n>>l>>r;
for(int i=0;i<n;i++){
s1[l[i]].push(i+1);
}
for(int i=0;i<n;i++){
s2[r[i]].push(i+1);
}
int ans=0;
for(int i='a';i<='z';i++){
while(!s1[i].empty()&&!s2[i].empty()){
vec.push_back(make_pair(s1[i].top(),s2[i].top()));
s1[i].pop(),s2[i].pop();
ans++;
}
while(!s1['?'].empty()&&!s2[i].empty()){
vec.push_back(make_pair(s1['?'].top(),s2[i].top()));
s1['?'].pop(),s2[i].pop();
ans++;
}
while(!s1[i].empty()&&!s2['?'].empty()){
vec.push_back(make_pair(s1[i].top(),s2['?'].top()));
s1[i].pop(),s2['?'].pop();
ans++;
}
}
while(!s1['?'].empty()&&!s2['?'].empty()){
vec.push_back(make_pair(s1['?'].top(),s2['?'].top()));
s1['?'].pop(),s2['?'].pop();
ans++;
}
cout<<ans<<endl;
for(int i=0;i<ans;i++){
cout<<vec[i].first<<" "<<vec[i].second<<endl;
}
return 0;
}
(仅供个人理解)