Poj Solution 2076

http://poj.org/problem?id=2076

#include<iostream>
#include"algorithm"
using namespace std;

int dist[101][101],n,m;

void init()
{
    int i,a,b,d,j,k;
    cin>>n>>m;
    
    for(i=0;i<n;i++)
    for(j=0;j<n;j++)
    dist[i][j]=9999;
    
    for(i=0;i<m;i++)
    {
        cin>>a>>b>>d;
        a--;b--;
        if(d<dist[a][b])
        {
            dist[a][b]=dist[b][a]=d;
        }
    }
    
    for(i=0;i<n;i++)
    dist[i][i]=0;
    
    for(k=0;k<n;k++)
    for(i=0;i<n;i++)
    for(j=0;j<n;j++)
    if(dist[i][k]+dist[k][j]<dist[i][j])
    dist[i][j]=dist[i][k]+dist[k][j];

    return ;
}
int answer[101];
int c1,c2;
int cmp(int a,int b)
{
    return dist[a][c2]-dist[a][c1]>dist[b][c2]-dist[b][c1]||
        (dist[a][c2]-dist[a][c1]==dist[b][c2]-dist[b][c1]&&a<b);
}

void doit()
{
    int index[101];long best=99999999,now;
    int bestk;
    int i,j;
    
    for(c2=0;c2<n;c2++)
    for(c1=c2+1;c1<n;c1++)
    {
        bestk=-1;

        for(i=0,j=0;i<n;i++)
            if(i!=c1&&i!=c2)
                index[j++]=i;
        
        std::sort(&index[0],&index[j],cmp);
        
        now=0;
        
        for(i=0;i<n;i++)
        if(i!=c1&&i!=c2)now+=(n-1)*dist[i][c2];
                
        now+=(n-1)*dist[c1][c2];
        
        if(now<best)
        {
            bestk=0;
            best=now;
        }
        
        for(i=1;i<n-1;i++)
        {
            now-=i*(n-i)*dist[c1][c2];
            now+=(i+1)*(n-i-1)*dist[c1][c2];
            now+=(dist[index[i-1]][c1]-dist[index[i-1]][c2])*(n-1);
            if(now<best)
            {
                bestk=i;
                best=now;
            }
        }
        
        if(bestk>=0)
        {
            for(i=0;i<bestk;i++)
                answer[index[i]]=c1+1;
            
            for(;i<n-2;i++)
                answer[index[i]]=c2+1;
                
            answer[c1]=0;
            answer[c2]=0;
        }
    }
    return;
}
            
int main()
{
    int t,i;
    cin>>t;
    while(t--)
    {
        init();
        doit();
        for(i=0;i<n;i++)
        {
            if(i)cout<<' ';
            cout<<answer[i];
        }
        cout<<endl;
    }
    return 0;
}
											
This entry was posted in poj. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *