1569. Networking the “Iset”

原文链接: http://www.cnblogs.com/liulangye/archive/2013/01/26/2878175.html

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

枚举每一个点为起点 进行广搜 比较每次搜到的树  选择最优的一种结果

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<map>
#include<vector>
#include<stack>
#include<set>
#include<map>
#include<queue>
#include<algorithm>
#include<cmath>
#define LL long long
//#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
const int INF=0x3f3f3f3f;
const int N=205;
const int M=200005;
int l[M],r[M];
bool instal[M],tmp[M];
int head[N],I;
struct node
{
    int j,next;
    int k;
}edge[M];
int dist[N];
bool final[N];
int D;
int n,m;
void add(int i,int j,int k)
{
    edge[I].j=j;
    edge[I].k=k;
    edge[I].next=head[i];
    head[i]=I++;
}
void bfs(int x1)
{
    memset(final,true,sizeof(final));
    memset(dist,-1,sizeof(dist));
    memset(tmp,false,sizeof(tmp));
    queue<int>qt;
    qt.push(x1);
    dist[x1]=0;
    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(dist[j]==-1)
            {
                final[x]=false;
                dist[j]=dist[x]+1;
                //cout<<edge[t].k<<endl;
                tmp[edge[t].k]=true;
                qt.push(j);
            }
        }
    }

    int k1=-1,k2=-1;
    for(int i=1;i<=n;++i)
    if(final[i])
    {
        if(k2==-1||dist[i]>dist[k2])
        k2=i;
        if(k1==-1||dist[k2]>dist[k1])
        swap(k1,k2);
    }
    int d=0;
    if(k1!=-1)
    d+=dist[k1];
    if(k2!=-1)
    d+=dist[k2];

    if(D==-1||d<D)
    {//cout<<d<<" "<<D<<endl;
        D=d;
        for(int i=1;i<=m;++i)
        instal[i]=tmp[i];
    }

}
int main()
{
    //freopen("data.in","r",stdin);
    while(cin>>n>>m)
    {
        memset(head,-1,sizeof(head));
        I=0;
        D=-1;
        for(int i=1;i<=m;++i)
        {
            cin>>l[i]>>r[i];
            add(l[i],r[i],i);
            add(r[i],l[i],i);
        }
        for(int i=1;i<=n;++i)
        bfs(i);
        for(int i=1;i<=m;++i)
        if(instal[i])
        cout<<l[i]<<" "<<r[i]<<endl;
    }
    return 0;
}

  

转载于:https://www.cnblogs.com/liulangye/archive/2013/01/26/2878175.html

猜你喜欢

转载自blog.csdn.net/weixin_30699831/article/details/94791819