Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define icin(x) scanf("%d",&x)
- #define pb push_back
- #define LL long long
- #define F first
- #define S second
- #define eps ((double)1e-8)
- #define maxn 109
- #define maxm 100009
- using namespace std;
- int a[maxn][maxn],b[maxn][maxn];
- int r,c;
- bool valid(int i,int j)
- {
- if(i<1 || i>r)
- return 0;
- if(j<1 || j>c)
- return 0;
- return 1;
- }
- int main()
- {
- int t;
- icin(t);
- int x =0;
- while(t--)
- {
- x++;
- icin(r);icin(c);
- vector< pair<int,int> > vec[1001];
- int vis[100][100];
- memset(vis,0,sizeof(vis));
- memset(b,0,sizeof(b));
- for(int i=1;i<=r;i++)
- {
- for(int j=1;j<=c;j++)
- {
- icin(a[i][j]);
- vec[a[i][j]].pb({i,j});
- }
- }
- int ans =0;
- for(int num=1;num<=1000;num++)
- {
- if(num>1)
- {
- for(int i=0;i<vec[num-1].size();i++)
- {
- vis[vec[num-1][i].F][vec[num-1][i].S]=0;
- }
- }
- for(int i=0;i<vec[num].size();i++)
- {
- int row = vec[num][i].F,col=vec[num][i].S;
- vector< pair<int,int> > store;
- queue< pair<int,int> > q;
- if(vis[row][col]==0)
- {
- //cout << row << " " << col << endl;
- int ch = 1234567;
- store.pb({row,col});
- q.push({row,col});
- vis[row][col]=1;
- while(!q.empty())
- {
- auto p = q.front();
- q.pop();
- int t1=p.F,t2=p.S;
- if(valid(t1-1,t2))
- {
- if(a[t1-1][t2]==num && vis[t1-1][t2]==0)
- {
- store.pb({t1-1,t2});
- vis[t1-1][t2]=1;
- q.push({t1-1,t2});
- }
- else if(a[t1-1][t2]!=num)
- ch = min(a[t1-1][t2],ch);
- }
- else
- ch=0;
- if(valid(t1+1,t2))
- {
- if(a[t1+1][t2]==num && vis[t1+1][t2]==0)
- {
- store.pb({t1+1,t2});
- vis[t1+1][t2]=1;
- q.push({t1+1,t2});
- }
- else if(a[t1+1][t2]!=num)
- ch = min(a[t1+1][t2],ch);
- }
- else
- ch=0;
- if(valid(t1,t2-1))
- {
- if(a[t1][t2-1]==num && vis[t1][t2-1]==0)
- {
- store.pb({t1,t2-1});
- vis[t1][t2-1]=1;
- q.push({t1,t2-1});
- }
- else if(a[t1][t2-1]!=num)
- ch = min(a[t1][t2-1],ch);
- }
- else
- ch=0;
- if(valid(t1,t2+1))
- {
- if(a[t1][t2+1]==num && vis[t1][t2+1]==0)
- {
- store.pb({t1,t2+1});
- vis[t1][t2+1]=1;
- q.push({t1,t2+1});
- }
- else if(a[t1][t2+1]!=num)
- ch = min(a[t1][t2+1],ch);
- }
- else
- ch=0;
- }
- // cout << num << " " << ch << endl;
- if(ch<num || ch==1234567)
- continue;
- else
- {
- for(int j=0;j<store.size();j++)
- {
- ans += (ch - num);
- a[store[j].F][store[j].S] = ch;
- vec[ch].pb({store[j].F,store[j].S});
- }
- }
- }
- }
- }
- // for(int i=1;i<=r;i++)
- // {
- // for(int j=1;j<=c;j++)
- // cout << a[i][j] << " ";
- // cout << endl;
- // }
- cout << "Case #" << x << ": " << ans << endl;
- }
- }
Add Comment
Please, Sign In to add comment