Sorting almost ordered sequence [closed] - algorithm

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a sequence, which can be really long.
I am inputing the number of elements and the special number, which will cut my sequence into the parts, for example:
10 2
here I have 10 numbers and 5 blocks (10/2)
I must sort this sequence using merge sort
here is the code:
int number_of_elements, k;
cin >> number_of_elements;
cin >> k;
int* massiv_1 = new int[k];
int* massiv_2 = new int[k];
int* resulted_massiv = new int[number_of_elements];
for(int i = 0; i < number_of_elements; i++) {
resulted_massiv[i] = 0;
}
int i = 0;
while( i < number_of_elements) {
int counter_1 = 0;
int counter_2 = 0;
cin >> massiv_1[counter_1];
counter_1++;
if( i != 0 ) {
quick_Sort( massiv_1, k-1 );
for(; counter_2 < k; counter_2++) {
cin >> massiv_2[counter_2];
counter_2++;
}
quick_Sort( massiv_2, k-1 );
merge(massiv_1, k, massiv_2, k, resulted_massiv, i);
}
counter_1 = 0;
counter_2 = 0;
i = i + k;
}
here is the merge sort
void merge(int *a, int a_len, int *b, int b_len, int *c, int z1) {
int i = 0, j = 0;
for(;i < a_len && j < b_len;) {
if(a[i] < b[j]) {
c[z1] = a[i];
++i;
} else {
c[z1] = b[j];
j++;
}
}
if(i == a_len) {
for(; j < b_len; ++j) {
c[z1] = b[j];
}
} else {
for(; i < a_len; ++i) {
c[z1] = a[i];
}
}
}
In other words here is the algorithm:
First I cut sequnce into k parts
I am going through it, if I see the index = k, I am using quick_sort,
then I go to the nearest block and also use quick_sort,
and then I am using merge sorting puting it into other array
...and this I am doing till the end of the sequence
this algorithm doesn't work, if enter this:
10 4
0 4 3 2 1 8 7 6 5 9
it must sort this sequence, but it shows this:
0 0 0 0 4 0 0 0 8 0
I can't get it
I will really appreciate your help, thank you in advance!!!

You always write in single c[z1] element in merge function, and never increment z1 index.
Index in "c" array should be incremented at every step, so you can use c[z1++] everywhere in the funcion

Related

Heap updating order

here's a working code for heapsort algorithm, my question is if in heap creation I swap the condition in the code with
for ( int i = 0 ; i < dim/2-1; i ++)
that I think it's the for cycle but in reverse order and I think that the process of updating the heap is quite the same (in my head we go trough updating the heap condition for every index from 0 to the end of the array),why the algorithm won't work anymore? It's wrong written the other condition or simply the algorithm is designed to work decreasing the index i? Thank you
#include <stdio.h>
void Scambia( int *px, int *py);
void Aggiornaheap( int *pa, int i, int j);
int main(void)
{
int a[256];
int n;
int dim = 0;
// Lettura dell’input da tastiera
while (scanf("%d\n", &n) == 1)
{
a[dim] = n;
dim++;
}
// heap creation
for ( int i = dim/2-1 ; i >= 0; i --)
{
Aggiornaheap(a, i, dim);
}
//Heapsort
for ( int i = dim-1; i >= 0; i --)
{
Scambia(&a[0], &a[i]);
Aggiornaheap(a, 0, i-1);
}
for ( int i = 0; i < dim; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
void Scambia( int *px, int *py)
{
int temp;
temp = *px;
*px = *py;
*py = temp;
}
void Aggiornaheap( int *pa, int i, int j)
{
int k;
if ( 2*i == j )
{
if ( pa[i] < pa[j])
Scambia(&pa[i], &pa[j]);
}
if ( 2*i < j )
{
if ( pa[2*i] > pa[2*i+1] )
k = 2*i;
else k = 2*i+1;
if ( pa[i] < pa[k])
{
Scambia(&pa[i], &pa[k]);
Aggiornaheap(pa, k, j);
}
}
}
It is necessary that the nodes are visited in reverse order. The algorithm will not do its job correctly if you change that order.
Take for instance this input tree that needs to be heapified into a min-heap: [2,4,3,1], which can be visualised as follows:
2
/ \
4 3
/
1
Then note how it will be impossible for the 1 value to bubble to the top, when you alter the for loop to go forward. Let's just try this. When i==0 nothing is swapped, because 2 is less than its children. When i==1 then 4 will be swapped with 1, and then the loop has finished. Clearly, this has not created a valid heap.
If however we start with i==1, which triggers the swap of 1 with 4, and only then have i==0, then we will again swap 1 to move up:
1
/ \
2 3
/
4
One comment about your code. It looks like you work with zero-indexed arrays, with the root element at 0, but in that case the children are at i*2+1 and i*2+2, not one less like we see in your code.

Develop an algorithm

I participated in a programming competition at my University. I solved all the questions except this one. Now I am practicing this question to improve my skills. But I can't figure out the algorithm. If there is any algorithm existing please update me. Or any similar algorithm is present then please tell me I will change it according to this question.
This is what I want to do.
The First line of input is the distance between two points.
After that, each subsequent line contains a pair of numbers indicating the length of cable and quantity of that cable. These cables are used to join the two points.
Input is terminated by 0 0
Output:
The output should contain a single integer representing the minimum number of joints possible to build the requested length of cableway. If no solution possible than print "No solution".
Sample Input
444
16 2
3 2
2 2
30 3
50 10
45 12
8 12
0 0
Sample Output
10
Thanks guys. I found a solution from "Perfect subset Sum" problem and then made a few changes in it. Here's the code.
#include <bits/stdc++.h>
using namespace std;
bool dp[100][100];
int sizeOfJoints = -1;
void display(const vector<int>& v)
{
if (sizeOfJoints == -1)
{
sizeOfJoints = v.size() - 1;
}
else if (v.size()< sizeOfJoints)
{
sizeOfJoints = v.size() - 1;
}
}
// A recursive function to print all subsets with the
// help of dp[][]. Vector p[] stores current subset.
void printSubsetsRec(int arr[], int i, int sum, vector<int>& p)
{
// If sum becomes 0
if (sum == 0)
{
display(p);
return;
}
if(i<=0 || sum<0)
return;
// If given sum can be achieved after ignoring
// current element.
if (dp[i-1][sum])
{
// Create a new vector to store path
//vector<int> b = p;
printSubsetsRec(arr, i-1, sum, p);
}
// If given sum can be achieved after considering
// current element.
if (sum >= arr[i-1] && dp[i-1][sum-arr[i-1]])
{
p.push_back(arr[i-1]);
printSubsetsRec(arr, i-1, sum-arr[i-1], p);
p.pop_back();
}
}
// all subsets of arr[0..n-1] with sum 0.
void printAllSubsets(int arr[], int n, int sum)
{
if (n == 0 || sum < 0)
return;
// If sum is 0, then answer is true
for (int i = 0; i <= n; i++)
dp[i][0] = true;
// If sum is not 0 and set is empty, then answer is false
for (int i = 1; i <= sum; i++)
dp[0][i] = false;
// Fill the subset table in botton up manner
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= sum; j++)
{
if(j<arr[i-1])
dp[i][j] = dp[i-1][j];
if (j >= arr[i-1])
dp[i][j] = dp[i-1][j] ||
dp[i - 1][j-arr[i-1]];
}
}
if (dp[n][sum] == false)
{
return;
}
// Now recursively traverse dp[][] to find all
// paths from dp[n-1][sum]
vector<int> p;
printSubsetsRec(arr, n, sum, p);
}
// Driver code
int main()
{
int input[2000];
int inputIndex = 0;
int i = 0;
int distance = 0;
cout<< "Enter Input: " <<endl;
cin>> distance;
while(true)
{
int temp1 = 0;
int temp2 = 0;
cin>> temp1;
cin>> temp2;
if (temp1 == 0 && temp2 == 0)
{
break;
}
for (i = 0; i < temp2; i++)
input[inputIndex++] = temp1;
}
cout<< "Processing output. Please wait: " <<endl;
printAllSubsets(input, inputIndex, distance);
if(sizeOfJoints != -1)
cout<<sizeOfJoints;
else
cout<<"No Solution Possible";
return 0;
}

How do for loops work in C? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
In the following for loop, how does the flow of control work?
int k = 0, x = 7, n = 5;
for (int i = 0; i < x; i++) {
/* When j == 4 in first cycle, k == 5 */
for (j = 0; j < n; j++) {
b[i][j] = a[k];
k++;
}
i++; // i is 2 here.
for (m = j; m >= 0; m--) {
b[i][m] = a[k];
k++;
}
}
First of all, x and n never change, so let's put their values in the for loops and remove them from the code, to make it easier to understand.
int k = 0;
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 5; j++) {
b[i][j] = a[k];
k++;
}
i++;
for (int m = j; m >= 0; m--) {
b[i][m] = a[k];
k++;
}
}
• Before first iteration of the i loop
i = 0;
k = 0;
j loop goes from 0 .. 4
b[0][0] = a[0]; // b[i][j] = a[k]
b[0][1] = a[1];
b[0][2] = a[2];
b[0][3] = a[3];
b[0][4] = a[4];
j loop exits because j has reached 5.
k is same as j (starts at 0, incremented like j)
i is incremented to become 1
m loop goes from 5 .. 0
b[1][5] = a[5]; // b[i][m] = a[k]
b[1][4] = a[6];
b[1][3] = a[7];
b[1][2] = a[8];
b[1][1] = a[9];
b[1][0] = a[10];
m loop exits with
m = -1;
k = 11;
• At 2nd iteration of i loop:
i = 2; (because i *for* loop increments it)
k = 11;
j loop goes from 0 .. 4
b[2][0] = a[11]; // b[i][j] = a[k]
b[2][1] = a[12];
b[2][2] = a[13];
b[2][3] = a[14];
b[2][4] = a[15];
j loop exits because j has reached 5.
k = 16;
i is incremented to become 3
m loop goes from 5 .. 0
b[3][5] = a[16]; // b[i][m] = a[k]
b[3][4] = a[17];
b[3][3] = a[18];
b[3][2] = a[19];
b[3][1] = a[20];
b[3][0] = a[21];
.
.
.
I believe that for nested loops, the order of execution of statements follows this general form (starting from zero)
for (zero; one; ) {
two;
three;
four;
five;
for (six; seven; ten) {
eight;
nine;
}
}
Then in the second round
for (zero; twelve; eleven ) {
thirteen;
fourteen;
fifteen;
sixteen;
for (six; seventeen; twenty) {
eighteen;
nineteen;
}
}
second for loop tries to set the first row with a[k].
third for loop tries to set the second row with a[k].
The second for loop is going from j0 to jn-1 and the third for loop is going from jn to j1.
Kind of setting the rows in spiral fashion.

How can I tell when there are no solutions? Algorithm task [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
In a nutshell , given such a problem:
We load the number of players,
money each player,
and we load a string consisting of L i W
For example:
4 -> player's
2, 3, 2, 1
2 is a money a first player, 3 a second etc.
and we load cycle
for example:
WLL -> W == win = cash + 1, L == lost = cash -1;
If to one of the players runs out of money, interrupts the game giving the number of games all players.
So:
The cycle repeats itself, so, we have WLLWLL ... WLL
2, 3, 2, 1
[WLL - first cycle] [WLL - next cycle]
so, we have:
3,2,1,2
next:
2,1,2,1
And in the end:
1,2,1,0
And we count the number of games - 12
It is also the case when the players never lose , you then write -1
So,
my question is: How do I write a program that would calculate it as efficiently and if the game would never end wrote -1?
I have something like that:
enter code here
#include<vector>
#include<iostream>
using namespace std;
int main()
{
int n, m, ile_gier;
bool nieskonczonosc = true;
cin >> n;
int tab[n];
for(int i = 0; i < n; i++)
{
cin >> tab[i];
}
cin >> m;
char znak[m];
cin >> znak;
int przesuniecie = n%m;
for(int i = 0; i < n; i++)
{
if(znak[i+przesuniecie] == 'W') nieskonczonosc = true;
}
if(nieskonczonosc == true) cout << "-1" << endl;
assume you have n players and a cicle with length k and the money each player has is greater then the n.
Therefore the next row will be shifted by n mod k. now you can calculate the money change after k rows (there the shift will definitely be 0) now you can calculate a state of the game and the number of rows where the game is nearly over (only if all changes after n rows are positive the game does not end) after that you can just calculate it straight forward.
PS You can improve this by taking n/gCd(n,k) rows because there the shift will be 0 as well. and you coould calculate the max Decrease of money in n rounds of all players. therefore the money of the player can get down to this value before you have to eval everything.....
Edit: Here is a sample code... it's not perfect, but you should be able to understand what I ment.....
#include<string>
#include<iostream>
#include<algorithm>
int bruteforce(int nPlayer, int* money, const std::string,int,bool doesEnd);
void calculateWin(int nPlayer, const std::string Cycle, int* changes);
int fastforward(int nPlayer, int* money,int* changes);
int main()
{
const int nPlayer = 4;
int money[nPlayer] = { 5,5,5,5 };
std::string Cycle = "WLL";
int changes[nPlayer];
calculateWin(nPlayer, Cycle, changes);
bool doesEnd = false;
for (int i = 0; i < nPlayer;i++)
if (changes[i] < 0)
{
doesEnd = true;
break;
}
if (doesEnd)
{
int fast = 0;
fast = fastforward(nPlayer, money, changes);
std::cout << "Games: " << fast*Cycle.length()*nPlayer+ bruteforce(nPlayer, money, Cycle, 0, 1) << std::endl;
}
else
{
int games = bruteforce(nPlayer, money, Cycle, 0, 0);
if (games == -1)
std::cout << "The Game will not end" << std::endl;
else
std::cout << "Games: " << games<<std::endl;
}
system("pause");
}
int bruteforce(int nPlayer, int* money, const std::string Cycle, int offset,bool doesend)
{
int nGames = 0;
int player = 0;
while (true)
{
player %= nPlayer;
offset %= Cycle.length();
for (int i = 0; i < nPlayer;i++)
if (money[i] <= 0) return nGames;
money[player] += Cycle[offset] == 'W' ? 1 : -1;
player++;
offset++;
nGames++;
if (!doesend&&nGames == nPlayer*Cycle.length())return -1;
}
}
void calculateWin(int nPlayer, const std::string Cycle, int* changes) // calculates the changes after nPlayer*Cycle.length() Games
{
int shift = nPlayer % Cycle.length();
for (int i = 0; i < nPlayer;i++)
{
changes[i] = 0;
for (int j = 0;j < Cycle.length();j++)
changes[i]+= Cycle[(j*shift+i)%Cycle.length()] == 'W'?1:-1;
}
}
int fastforward(const int nPlayer, int* money, int* changes)
{
int res = 2147483647; // max int
for (int i = 0; i < nPlayer;i++)
{
if(changes[i]<0)
res = std::min( (money[i] - nPlayer) / -changes[i],res);
}
if (res < 0)
return 0;
for (int i = 0; i < nPlayer; i++)
money[i] += res * changes[i];
return res;
}

High score in grid walk

There is an interesting game named one person game. It is played on a m*n grid. There is an non-negative integer in each grid cell. You start with a score of 0. You cannot enter a cell with an integer 0 in it. You can start and end the game at any cell you want (of course the number in the cell cannot be 0). At each step you can go up, down, left and right to the adjacent grid cell. The score you can get at last is the sum of the numbers on your path. But you can enter each cell at most once.
The aim of the game is to get your score as high as possible.
Input:
The first line of input is an integer T the number of test cases. The first line of each test case is a single line containing 2 integers m and n which is the number of rows and columns in the grid. Each of next the m lines contains n space-separated integers D indicating the number in the corresponding cell
Output:
For each test case output an integer in a single line which is maximum score you can get at last.
Constraints:
T is less than 7.
D is less than 60001.
m and n are less than 8.
Sample Input:
4
1 1
5911
1 2
10832 0
1 1
0
4 1
0
8955
0
11493
Sample Output:
5911
10832
0
11493
I tried it but my approach is working very slow for a 7x7 grid.I am trying to access every possible path of the grid recursively and comparing the sum of every path.Below is my code
#include<iostream>
#include <algorithm>
#include <stdio.h>
using namespace std;
int max(int a,int b,int c, int d)
{
int max = a;
if(b>max)
max = b;
if(c>max)
max = c;
if(d>max)
max = d;
return max;
}
int Visit_Component( int (*A)[8], int Visit[8][8], int m,int n , int row, int col)
{
if ( ( row >= m ) || (col >= n ) || (col < 0) || (row < 0) || A[row][col] == 0 || Visit[row][col] == 1 )
{
return 0;
}
else
{
Visit[row][col] = 1;
int a= 0,b=0,c=0,d=0,result =0;
a = Visit_Component( A, Visit,m,n, row+1, col);
b = Visit_Component( A, Visit,m,n, row, col +1);
c = Visit_Component( A, Visit,m,n, row, col -1);
d = Visit_Component( A, Visit,m,n, row-1, col );
Visit[row][col] = 0;
result = A[row][col] + max(a,b,c,d);
return result;
}
}
int main(){
int T;
scanf("%d",&T);
for(int k =0; k<T;k++)
{
int N ;
int M;
int count = 0;
int maxcount = 0;
scanf("%d %d",&M,&N);
int C[8][8];
int visit[8][8];
for(int i = 0; i < M; i++)
for(int j = 0; j < N; j++)
{
scanf("%d",&C[i][j]);
visit[i][j] = 0;
}
for( int i= 0 ; i< M ; i++ )
{
for( int j =0; j< N ; j++ )
{
count = Visit_Component( C, visit,M,N, i, j);
if(count > maxcount)
{
maxcount = count;
}
}
}
printf("%d\n",maxcount);
}
return 0;
}
Please suggest me how to optimize this approach or a better algorithm.
As Wikipedia article on Travelling salesman problem suggests, there are exact algorithms, solving this task quickly. But it is hard to find any. And they are, most likely, complicated.
As for optimizing OP's approach, there are several possibilities.
It's easier to start with simple micro-optimization: condition Visit[row][col] == 1 is satisfied with highest probability, so it should come first.
Also it is reasonable to optimize branch-and-bound algorithm with dynamic programming to avoid some repeated calculations. Memorizing calculation results in simple hash table for the cases of up to 19 visited cells improves performance by more than 25% (and more may be expected for some improved hash table). Here is the modified code snippet:
#include<iostream>
#include <algorithm>
#include <stdio.h>
using namespace std;
int max(int a,int b,int c, int d)
{
int max = a;
if(b>max)
max = b;
if(c>max)
max = c;
if(d>max)
max = d;
return max;
}
typedef unsigned long long ull;
static const int HS = 10000019;
static const int HL = 20;
struct HT {
ull v;
int r;
int c;
};
HT ht[HS] = {0};
int Visit_Component(
int (*A)[8], ull& Visit, int m,int n , int row, int col, int x)
{
if ( (Visit & (1ull << (8*row+col))) || ( row >= m ) || (col >= n ) ||
(col < 0) || (row < 0) || A[row][col] == 0)
{
return 0;
}
else
{
if (x < HL)
{
HT& h = ht[(Visit+4*row+col)%HS];
if (h.v == Visit && h.r == row && h.c == col)
return 0;
}
Visit |= (1ull << (8*row+col));
int a= 0,b=0,c=0,d=0,result =0;
a = Visit_Component( A, Visit,m,n, row+1, col, x+1);
b = Visit_Component( A, Visit,m,n, row, col +1, x+1);
c = Visit_Component( A, Visit,m,n, row, col -1, x+1);
d = Visit_Component( A, Visit,m,n, row-1, col , x+1);
Visit &= ~(1ull << (8*row+col));
result = A[row][col] + max(a,b,c,d);
if (x < HL)
{
HT& h = ht[(Visit+4*row+col)%HS];
h.v = Visit;
h.r = row;
h.c = col;
}
return result;
}
}
int main(){
int T;
scanf("%d",&T);
for(int k =0; k<T;k++)
{
int N ;
int M;
int count = 0;
int maxcount = 0;
scanf("%d %d",&M,&N);
int C[8][8];
ull visit = 0;
for(int i = 0; i < M; i++)
for(int j = 0; j < N; j++)
{
scanf("%d",&C[i][j]);
}
for( int i= 0 ; i< M ; i++ )
{
for( int j =0; j< N ; j++ )
{
count = Visit_Component( C, visit,M,N, i, j, 0);
if(count > maxcount)
{
maxcount = count;
}
}
}
printf("%d\n",maxcount);
}
return 0;
}
And much more improvements may be done by pre-processing the input matrix. If there are no zeros in the matrix or if there is only one zero in the corner, you may just sum all the values.
If there is only one zero value (not in the corner), at most one non-zero value should be excluded from the sum. If you invent an algorithm, that determines the subset of cells, from which one of the cells must be removed, you can just select the smallest value from this subset.
If there are two or more zero values, use branch-and-bound algorithm: in this case it is about 20 times faster, because each zero value in input matrix means approximately fivefold speed increase.
One optimization that I can think of is to apply Dijkstra's algorithm. This algorithm will give you a minimum (in your case maximum) path for a particular source node to all destination nodes.
In this example, the first step would be to build a graph.
And because you don't know the source node to start at, you will have to apply Dijkstra's algorithm for each node in the grid. The time complexity will be better than your recursion method because for a particular source node, when finding a maximum path Dijkstra's algorithm does not go through all the possible paths.
#include<iostream>
#include<vector>
using namespace std;
vector<vector<int> >A;
vector<vector<bool> >test;
vector<vector<bool> >test1;
int sum_max=0;
int m,n;
vector<vector<bool> > stamp;
void color1(int i,int j,vector<vector<bool> >temp_vector,vector<vector<bool> > st,int summ){
temp_vector[i][j]=false;summ+=A[i][j];st[i][j]=true;
//1.1
if(i+1<m && temp_vector[i+1][j]){
if(test1[i+1][j]){
if(sum_max<(summ)){sum_max=summ;stamp=st;}
}
else{color1(i+1,j,temp_vector,st,summ);}
}
//1.2
if(i+1<m){if(!temp_vector[i+1][j]){ if(sum_max<(summ)){sum_max=summ;}}}
if(i+1>=m){if(sum_max<(summ)){sum_max=summ;}}
//2
if(i-1>=0 && temp_vector[i-1][j]){
if(test1[i-1][j]){
if(sum_max<(summ)){sum_max=summ;}
}
else{ color1(i-1,j,temp_vector,st,summ);}
}
//2.2
if(i-1>=0){if(!temp_vector[i-1][j]){ if(sum_max<(summ)){sum_max=summ;}}}
if(i-1<0){if(sum_max<(summ)){sum_max=summ;}}
//3
if(j+1<n && temp_vector[i][j+1]){
if(test1[i][j+1]){
if(sum_max<(summ)){sum_max=summ;}
}
else{ color1(i,j+1,temp_vector,st,summ);}}
//3.2
if(j+1<n){if(!temp_vector[i][j+1]){ if(sum_max<(summ)){sum_max=summ;}}}
if(j+1>=n){if(sum_max<(summ)){sum_max=summ;}}
//4
if(j-1>=0 && temp_vector[i][j-1]){
if(test1[i][j-1]){
if(sum_max<(summ)){sum_max=summ;}
}
else{ color1(i,j-1,temp_vector,st,summ);}}
//4.2
if(j-1>=0){if(!temp_vector[i][j-1]){ if(sum_max<(summ)){sum_max=summ;}}}
if(j+1<0){if(sum_max<(summ)){sum_max=summ;}}
}
void color(int i,int j){
test[i][j]=false;
if(i+1<m && test[i+1][j]){
color(i+1,j);}
if(i-1>=0 && test[i-1][j]){
color(i-1,j);
}
if(j+1<n && test[i][j+1]){
color(i,j+1);}
if(j-1>=0 && test[i][j-1]){color(i,j-1);}
}
int main(){
int tc;cin>>tc;
for(int i=0;i<tc;i++){
int mp,np;
cin>>mp;
cin>>np;m=mp;n=np;A.resize(m);test.resize(m);test1.resize(m);int sum=0;
vector<bool> ha1(m,1);
vector<bool> ha2(n,1);
for(int i=0;i<m;i++){A[i].resize(n);test[i].resize(n);test1[i].resize(n);
for(int j=0;j<n;j++){
cin>>A[i][j];sum+=A[i][j];
test[i][j]=true;test1[i][j]=false;
if(A[i][j]==0){test[i][j]=false;ha1[i]=false;ha2[j]=false;}
}
}cout<<endl;
for(int i=0;i<m;i++){cout<<" "<<ha1[i];} cout<<endl;
for(int i=0;i<n;i++){cout<<" "<<ha2[i];} cout<<endl;
cout<<"sum "<<sum<<"\n";
int temp_sum=0;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){//if(A[i][j]<=8845){cout<<"\nk "<<A[i][j]<<" "<<(8845-A[i][j]);}
if(test[i][j]){
if((i-1)>=0 && test[i-1][j] && (i+1)<m && test[i+1][j] && (j-1)>=0 && test[i][j-1] && (j+1)<n && test[i][j+1] && test[i-1][j-1] && test[i-1][j+1]&& test[i+1][j-1] && test[i+1][j+1]){
temp_sum+=A[i][j];test1[i][j]=true;}
}
// cout<<test1[i][j]<<" ";
}//cout<<"\n";
}
// /*
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(test1[i][j]){if(!((test1[i-1][j]||test1[i+1][j]) && (test1[i][j-1]||test1[i][j+1]))){
temp_sum-=A[i][j]; test1[i][j]=false;}
}
//
// cout<<test1[i][j]<<" ";
}//
// cout<<"\n";
}
// */
//cout<<"\n temp_sum is "<<temp_sum<<endl;
vector<vector<bool> > st(m,vector<bool>(n,0));st=test1;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(test[i][j] && (!test1[i][j])){
color1(i,j,test,st,0);
}}}
// cout<<"\nsum is "<<(sum_max+temp_sum)<<endl<<endl;
cout<<(sum_max+temp_sum)<<endl;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){cout<<stamp[i][j]<<" ";} cout<<endl;}
// cout<<max<<endl;
A.clear();
test.clear();
test1.clear();
sum_max=0;
}
cout<<endl;system("pause");
return 0;
}

Resources