UVA 124(求所有的拓扑序+字符串按行读入)

题意:第一行给定变量,第二行给定给定约束,每个约束包含两个变量, x y表示x<y

思路:DFS割边法求拓扑排序,每一次DFS完要记得还原现场。

注意:此题要按行读入,学习到了用getline(cin,s)按行读入 //s为string对象   ,然后用 istringstream is(s),while(is>>ch) ……

#include<bits/stdc++.h>
using namespace std;
#define inf 0x3f3f3f3f
#define ll long long
const int maxn=200005;
const double eps=1e-8;
const double PI = acos(-1.0);
#define lowbit(x) (x&(-x))
int in[150],g[150][150],cnt,vis[150];
char ans[30];
void dfs(int n)
{
    if(n==cnt)
    {
        for(int i=0;i<cnt;i++)
        {
            cout<<ans[i];
        }
        cout<<endl;
        return ;
    }
    for(int i='a';i<='z';i++)
    {
        if(!vis[i]&&in[i]==0)
        {
            for(int j='a';j<='z';j++)
            {
                if(g[i][j])
                {
                    in[j]--;
                }
            }
            vis[i]=1;
            ans[n]=i;
            dfs(n+1);
            for(int k='a';k<='z';k++)
            {
                if(g[i][k])
                    in[k]++;
            }
            vis[i]=0;
        }
    }
}
int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(0);
    string s;
    int t=0;
    while(getline(cin,s))
    {
        cnt=0;
        char ch1,ch2;
        memset(g,0,sizeof(g));
        memset(in,-1,sizeof(in));
        memset(vis,0,sizeof(vis));
        if(t)
            cout<<endl;
        t++;
        istringstream is(s);
        char ch;
        while(is>>ch)
        {
            in[ch]=0;
            cnt++;
        }
        getline(cin,s);
        istringstream iis(s);
        while(iis>>ch1>>ch2)
        {
            g[ch1][ch2]=1;
          //  cout<<ch1<<" "<<ch2<<endl;
            in[ch2]++;
        }
        /*for(int i=97;i<=122;i++)
        {
            cout<<in[i]<<endl;
        */
        dfs(0);
    }
    return 0;
}

 

posted @ 2018-08-06 21:45  MCQ  阅读(122)  评论(0编辑  收藏  举报