out_of_theblue10

Insule 2.0

Apr 10th, 2012
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.17 KB | None | 0 0
  1. #include <fstream>
  2. #include <cstring>
  3. #include <algorithm>
  4. #define MAXN 510
  5. #define MAXM 1000000
  6. #define MAXI 250010
  7. using namespace std;
  8. string s;
  9. const int dx[4]={1,0,-1,0};
  10. const int dy[4]={0,1,0,-1};
  11. int n,m,a[MAXN][MAXN],insula[MAXN][MAXN],p,k,t[MAXI],X[MAXM],Ind[MAXM],Y[MAXM],Cost[MAXM];
  12. int grupa(int x)
  13. {
  14.     if(t[x]==x) return x;
  15.     t[x]=grupa(t[x]);
  16.     return t[x];
  17. }
  18. void reunite(int x,int y)
  19. {
  20.     int key=grupa(x);
  21.     t[key]=grupa(y);
  22. }
  23. bool cmp(int x,int y)
  24. {
  25.     return Cost[x]<Cost[y];
  26. }
  27. void df(int x,int y)
  28. {
  29.     int i,j;
  30.     insula[x][y]=k;
  31.     for(int d=0;d<4;d++)
  32.     {
  33.         i=dx[d]+x; j=dy[d]+y;
  34.         if(a[i][j] and !insula[i][j]) df(i,j);
  35.     }
  36. }
  37. int main()
  38. {
  39.     int last,pod,nr,i,j;
  40.     ifstream fi("insule.in");
  41.     ofstream fo("insule.out");
  42.     fi>>n>>m;
  43.     getline(fi,s);
  44.     for(i=1;i<=n;i++)
  45.     {
  46.         getline(fi,s);
  47.         for(j=0;j<m;j++)
  48.         a[i][j+1]=s[j]-'0';
  49.     }
  50.     for(i=1;i<=n;i++)
  51.     for(j=1;j<=m;j++)
  52.     if(a[i][j] and !insula[i][j])
  53.     {
  54.         k++;
  55.         df(i,j);
  56.     }
  57.     //unesc pe linie
  58.     for(i=1,p=0;i<=n;i++)
  59.     {
  60.         last=0;
  61.         for(j=1;j<=m;j++)
  62.         if(a[i][j])
  63.         {
  64.             if(last and insula[i][last]!=insula[i][j])
  65.             {
  66.                 X[++p]=insula[i][last];
  67.                 Y[p]=insula[i][j];
  68.                 Cost[p]=j-last-1;
  69.                 Ind[p]=p;
  70.             }
  71.             last=j;
  72.         }
  73.     }
  74.     //unesc pe coloana
  75.     for(j=1;j<=m;j++)
  76.     {
  77.         last=0;
  78.         for(i=1;i<=n;i++)
  79.         if(a[i][j])
  80.         {
  81.             if(last and insula[last][j]!=insula[i][j])
  82.             {
  83.                 X[++p]=insula[last][j];
  84.                 Y[p]=insula[i][j];
  85.                 Cost[p]=i-last-1;
  86.                 Ind[p]=p;
  87.             }
  88.             last=i;
  89.         }
  90.     }
  91.     sort(Ind+1,Ind+p+1,cmp);
  92.     //Kruskal
  93.     for(i=1;i<=k;i++) t[i]=i;
  94.     for(i=1,nr=0,pod=0;i<=p and nr!=k-1;i++)
  95.     if(grupa(X[Ind[i]])!=grupa(Y[Ind[i]]))
  96.     {
  97.         reunite(X[Ind[i]],Y[Ind[i]]);
  98.         pod+=Cost[Ind[i]];
  99.         nr++;
  100.     }
  101.     if(nr<k-1) pod=-1;
  102.     fo<<pod<<"\n";
  103.     return 0;
  104. }
Advertisement
Add Comment
Please, Sign In to add comment