UPC-場所の交換(トポロジカルソート)

本旨:

s種とm種(友達かどうか)の関係を示し、次に長さnのシーケンスを示します。各位置は種を表します。
次の2つの条件が満たされた場合:
1。2つの隣接する種
2.2
つの間の友情関係種2つの種の位置を交換することができ、最小の語彙シーケンスを見つける

問題分析:
2つの種が友達でない場合、それらの相対的な位置は決して変化しません(制約条件)
種の制約が多いほど、シーケンスに表示されるのは遅くなります。

各位置の種を列挙して、マップを作成し(彼に制約がある種の場合)、エッジを接続できます

現時点では、すべての種と現在の種を前方にトラバースする必要はないため、時間計算量n * n
は、位置kに達したときに各種の最後の位置を見つけるだけで済みます。

シーケンスaaxaxaxb(xは任意の文字)など、同じ種間にも制約があるため、
aaaがシーケンスを配置しない場合、キューに参加するのはbの順番ではありません(トポロジカルソート)。 bの実際の制約は最後の文字aです。

コード

#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