题意:
给n,m个,给出n个字符串,再给出m个s1,s2,要求s1在s2之前,最小字典序排列,如果不符合就-1
思路:
拓扑排序,但如果用字符串来优先队列中一直tle,呜呜呜,然后又加上博客没有拓扑排序模板,我居然拓扑排序写错了,导致tle的原因
真正的思路,是先字典序排序,然后优先队列拓扑排序。
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define il inline
#define it register int
#define inf 0x3f3f3f3f
#define lowbit(x) (x)&(-x)
#define pii pair<int,int>
#define mak(n,m) make_pair(n,m)
#define mem(a,b) memset(a,b,sizeof(a))
#define mod 1000000007
const int maxn=3e4+10;
const int mo=1e9;
ll ksm(ll a,ll b){if(b<0)return 0;ll ans=1;while(b){if(b&1)ans=ans*a%mod;a=a*a%mod;b>>=1;}return ans;}
const double pi=acos(-1.0);
int t,n,m;
int ans[maxn],ge[maxn];
string s1,s2;
string na[maxn];
vector<int>v[maxn];
int fa[maxn];
priority_queue<int,vector<int>,greater<int> >q;
int main(){
ios::sync_with_stdio(false);
cin>>t;
int c=0;
while(t--){
mem(fa,0);mem(ge,0);
map<string,int>mp;
int len=0;
cin>>n>>m;
while(q.size()) q.pop();
for(int i=1;i<=n;i++){
cin>>na[i];v[i].clear();
}
sort(na+1,na+1+n);
for(int i=1;i<=n;i++) mp[na[i]]=i;
for(int i=1;i<=m;i++){
cin>>s1>>s2;
ge[mp[s2]]++;
v[mp[s1]].push_back(mp[s2]);
}
for(int i=1;i<=n;i++){
if(ge[i]==0){
q.push(i);fa[i]=true;
}
}
len=0;
while(q.size()){
int teep=q.top();
ans[++len]=teep;q.pop();
for(int i=0;i<v[teep].size();i++){
int tp=v[teep][i];
ge[tp]--;
if(ge[tp]==0&&!fa[tp]){
q.push(tp);
fa[tp]=true;
}
}
}
if(len!=n){
cout<<"Case #"<<++c<<":"<<endl;
cout<<"Impossible"<<endl;
}else{
cout<<"Case #"<<++c<<":"<<endl;
for(int i=1;i<=len;i++) cout<<na[ans[i]]<<endl;
}
}
return 0;
}