http://acm.timus.ru/problem.aspx?space=1&num=1544

bfs

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<map>
#include<vector>
#include<stack>
#include<set>
#include<map>
#include<queue>
#include<deque>
#include<algorithm>
#include<cmath>
#define LL long long
//#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
const int INF=0x3f3f3f3f;
const int N=105;
char p[N];
char a[N];
vector<char>vt[N];
int head[N],I;
struct node
{
    int j,next;
}edge[N*N];
void add(int i,int j)
{
    edge[I].j=j;
    edge[I].next=head[i];
    head[i]=I++;
}
bool bfs(int s,char c,int n)
{
    queue<int>qt;
    qt.push(s);
    a[s]=c;
    while(!qt.empty())
    {
        int x=qt.front();
        qt.pop();
        for(int t=head[x];t!=-1;t=edge[t].next)
        {
            int j=edge[t].j;
            if(a[j]!=c)
            {
                a[j]=c;
                qt.push(j);
            }
        }
    }
    for(int i=1;i<=n;++i)
    if(a[i]!=c)
    return false;
    return true;
}
int main()
{
    //freopen("data.in","r",stdin);
    int n,m;
    cin>>n>>m;
    memset(head,-1,sizeof(head));
    I=0;
    for(int i=1;i<=n;++i)
    vt[i].clear();
    bool flag=true;
    for(int i=1;i<=n;++i)
    {
        cin>>p[i];
        if(i>1&&p[i]!=p[i-1])
        flag=false;
    }
    if(flag)
    {cout<<"0"<<endl;return 0;}
    while(m--)
    {
        int l,r;
        cin>>l>>r;
        add(l,r);
        add(r,l);
    }
    for(int i=1;i<=n;++i)
    {
        for(int j=1;j<=n;++j)
        a[j]=p[j];
        while(!bfs(i,((a[i]=='J')?'E':'J'),n))
        vt[i].push_back(a[i]);
        vt[i].push_back(a[i]);
    }
    int k=1;
    for(int i=2;i<=n;++i)
    if(vt[i].size()<vt[k].size())
    k=i;
    cout<<vt[k].size()<<endl;
    for(unsigned int i=0;i<vt[k].size();++i)
    cout<<k<<" "<<vt[k][i]<<endl;
    return 0;
}

  

posted on 2013-02-20 19:39  夜->  阅读(202)  评论(0编辑  收藏  举报