out_of_theblue10

northcoders_insule.cpp

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