Introduction

This is my blog of programming, I take notes and leave codes of computer science problems I solved here. Be my guest to comment :)

Friday, October 19, 2012

UVA 259 - Software Allocation


This problem uses the max flow algorithm by Edmonds Karp
Problem link
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
const int maxn = 40;
const int oo=1000;
//----------------------------------
int res[maxn][maxn],p[maxn];
int mf,f,s,t,n,sum;
//----------------------------------
void readfile()
{
 string str;
 getline(cin,str);
 s=0; t=37; sum=0;
 for (int i=0; i<maxn; i++)
   for (int j=0; j<maxn; j++) res[i][j]=0;
 while (str!="")
 {
  char c = str[0];
  int value = int(str[1])-48;
  res[s][int(c)-64]+=value;
  sum += value;
  for (int i=3; i<str.length()-1; i++)
  {
   value = int(str[i])-48;
   res[int(c)-64][value+27]=1;
  }
  if (cin.eof()) break;
  getline(cin,str);
 }
 for (int i=27; i<=36; i++) res[i][t]=1;
}
//----------------------------------
void update(int v, int minE)
{
 if (v==s) { f=minE; return;}
 else if (p[v]!=-1)
 {
  update(p[v],min(minE,res[p[v]][v]));
  res[p[v]][v]-=f;
  res[v][p[v]]+=f;
 }
}
//----------------------------------
int MaxFlow()
{
 int result=0;
 while (true)
 {
  f=0;
  int dist[maxn]; 
  for (int i=0; i<maxn; i++) dist[i]=1000;
  dist[s]=0;
  int q[maxn*maxn],head=1,tail=1; memset(p,-1,sizeof(p));
  q[head]=s; 
  while (head<=tail)
  {
   int u=q[head]; head++;
   if (u==t) break;
   for (int v=0; v<maxn; v++)
    if (res[u][v]>0 && dist[v]==oo)
    {
     dist[v]=dist[u]+1;
     q[++tail]=v;
     p[v]=u;
    }
  }
  update(t,oo);
  if (f==0) break;
  result += f;
 }
 return(result);
}
//----------------------------------
int main()
{
 while (!cin.eof())
 {
  readfile();
  mf = MaxFlow();
  if (mf==sum)
  {
   for (int i=27; i<=36; i++)
   {
    bool flag = false;
    for (int j=1; j<=27; j++)
     if (res[i][j]==1) 
     {
      cout << char(j+64);
      flag = true;
      break;
     }
    if (!flag) cout << "_";
   }
   cout << endl;
  }
  else cout << "!" << endl;
 }
 return 0;
}
//----------------------------------


No comments:

Post a Comment