【codeforces 510C】Fox And Names

【题目链接】:http://codeforces.com/contest/510/problem/C

【题意】

给你n个字符串;
问你要怎么修改字典序;
(即原本是a,b,c..z现在你可以修改每个字母在字典序中的位置了);
才能使得这n个字符串是字典序升序的;

【题解】

对于第i个字符串;
让他和第i+1..n个字符串比较->j;
找到第一个不同的位置pos;
然后
必然是要
s[i][pos]< s[j][pos]的;
拓扑排序!
即s[i][pos]建一条边指向s[j][pos]
然后做拓扑排序就好;
如果某个串是另外一个串的子串;
则如果s[i]是s[j]的子串,那么可行,否则无解;

【Number Of WA

0

【完整代码】

#include <bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define ps push_back
#define fi first
#define se second
#define rei(x) cin >> x
#define pri(x) cout << x
#define ms(x,y) memset(x,y,sizeof x)

typedef pair<int,int> pii;
typedef pair<LL,LL> pll;

const int dx[9] = {0,1,-1,0,0,-1,-1,1,1};
const int dy[9] = {0,0,0,-1,1,-1,1,-1,1};
const double pi = acos(-1.0);
const int MAXC = 26+10;
const int N = 100+10;

int a[MAXC][MAXC],n,du[MAXC],cnt=0;
queue <int> dl;
string s[N];
vector <int> ans;

int main()
{
    //freopen("F:\\rush.txt","r",stdin);
    ios::sync_with_stdio(false);
    rei(n);
    rep1(i,1,n)
        rei(s[i]);
    rep1(i,1,n)
    {
        rep1(j,i+1,n)
        {
            int ma = min(int(s[i].size()),int(s[j].size()));
            int pos = -1;
            rep1(k,0,ma-1)
                if (s[i][k]!=s[j][k])
                {
                    pos = k;
                    break;
                }
            if (pos==-1)
            {
                if (int(s[i].size())>int(s[j].size()))
                    return pri("Impossible"<<endl),0;
                else
                    continue;
            }
            int x = s[i][pos]-'a'+1,y = s[j][pos]-'a'+1;
            if (a[x][y]) continue;
            du[y]++;
            a[x][y]=1;
        }
    }
    rep1(i,1,26)
        if (du[i]==0)
            dl.push(i),cnt++,ans.ps(i);
    while (!dl.empty())
    {
        int x = dl.front();
        dl.pop();
        rep1(j,1,26)
            if (a[x][j])
            {
                a[x][j] = 0;
                du[j]--;
                if (du[j]==0)
                {
                    dl.push(j);
                    ans.ps(j);
                    cnt++;
                }
            }
    }
    if (cnt==26)
        rep1(i,0,25)
            putchar(ans[i]+'a'-1);
    else
        return pri("Impossible"<<endl),0;
    //printf("\n%.2lf sec \n", (double)clock() / CLOCKS_PER_SEC);
    return 0;
}
posted @ 2017-10-04 18:44  AWCXV  阅读(103)  评论(0编辑  收藏  举报