UPC - Swapping Places (拓扑排序)

题目大意:

给你s种物种,和m个物种之间的关系(朋友或者不是朋友关系),然后在给你一个长度为n的序列每个位置代表一个物种
当满足一下两个条件时:
1 . 两个物种相邻
2. 两个物种时朋友关系
这两个物种的位置可以交换,求字典序最小的序列

题目分析:
如果两个物种不是朋友关系,那么他们的相对位置永远不会改变(约束条件)
某个物种约束条件越多,他在序列中出现的位置应该越靠后,

可以枚举每个位置的物种建图(对于对他有约束的物种)连边

这个时候并不需要向前遍历所有的物种和当前物种连边,这样时间复杂度n*n
只需要找每个物种到k这个位置时最后一个出现的位置就ok

因为同种物种之间也会产生约束,如序列axaxxaxb(x为任意字母)
如果aaa不排好序列的话,是轮不到b入队的(拓扑排序时),也就是实际对b产生约束的是最后一个a字母。

Code

#include<iostream>
#include<algorithm>
#include<math.h>
#include<queue>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <stack>
#include <map>
#include <set>
#include <vector>


using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
typedef unsigned long long ull;
const int inf = 0x3f3f3f3f;
const int maxn = 2e5 + 7;
const ll mod = 1000000007;

#define mst(x, a) memset( x,a,sizeof(x) )
#define rep(i, a, b) for(int i=(a);i<=(b);++i)
#define dep(i, a, b) for(int i=(a);i>=(b);--i)

ll read() {
    
    
    ll x = 0;
    char ch = getchar();
    while(ch < '0' || ch > '9')ch = getchar();
    while(ch >= '0' && ch <= '9')x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
    return x;
}

void out(ll x) {
    
    
    int stackk[40];
    if (x < 0) {
    
    
        putchar('-');
        x = -x;
    }
    if (!x) {
    
    
        putchar('0');
        return;
    }
    int top = 0;
    while (x) stackk[++top] = x % 10, x /= 10;
    while (top) putchar(stackk[top--] + '0');
}
vector<int>v[maxn];
int s,l,n,cnt,link[233][233],a[maxn],pre[maxn],d[maxn];
string str[233];
map<string,int>mp;

int main() {
    
    
    cin>>s>>l>>n;
    for(int i=1 ; i<=s ; i++)   cin>>str[i];
    sort(str+1,str+1+s);
    for(int i=1 ; i<=s ; i++)  if(!mp[str[i]]) mp[str[i]]=++cnt;

    for(int i=1 ; i<=l ; i++) {
    
    
        string t1,t2;
        cin>>t1>>t2;
        int x=mp[t1];
        int y=mp[t2];
        link[x][y]=1;
        link[y][x]=1;
    }

    for(int i=1 ; i<=n ; i++) {
    
    
        string temp;
        cin>>temp;
        a[i]=mp[temp];
    }

    for(int i=1 ; i<=n ; i++) {
    
    
        for(int j=1 ; j<=s ; j++) {
    
    
            int x=a[i];
            int y=j;
            if(link[x][y]) continue;
            if(pre[j]==0) continue;
            v[pre[j]].push_back(i);
            d[i]++;
        }
        pre[a[i]]=i;
    }

    for(int i=1 ; i<=n ; i++) if(d[i]==0) q.push({
    
    a[i],i});
    priority_queue<PII>q;
    while(q.size()) {
    
    
        PII fr=q.top();
        q.pop();
        int c=fr.first;
        int dian=fr.second;
        cout<<str[c]<<" ";
        for(int e:v[dian]) {
    
    
            d[e]--;
            if(d[e]==0) q.push({
    
    a[e],e});
        }
    }
    return 0;
}
/**
3 2 6
ANTILOPE
CAT
ANT
CAT ANTILOPE
ANTILOPE ANT
ANT CAT CAT ANTILOPE CAT ANT
**/


猜你喜欢

转载自blog.csdn.net/wmy0536/article/details/109607552
UPC
今日推荐