1581C - Portal - CodeForces Solution


brute force dp greedy implementation *1700

Please click on ads to support us..

C++ Code:

#include<iostream>
#include<cstring>
#include<vector>
using namespace std;
using ll = long long;
const int mod = 1e9+7;
const int N = 405;
int dp[N][N];
char s1[N][N];
void suan(int l1,int r1,int x)
{
	dp[l1][r1]=x;
	dp[l1][r1]+=dp[l1-1][r1]+dp[l1][r1-1]-dp[l1-1][r1-1];
}
int he (int l1,int r1,int l2,int r2)
{
	int res = 0;
	res=dp[l2][r2]-dp[l1-1][r2]-dp[l2][r1-1]+dp[l1-1][r1-1];
	return res;
}
int main()
{
	ll t;
	cin>>t;
	while(t--)
	{
		int n,m;
		cin>>n>>m;
		for(int i=1;i<=n;i++)
			scanf("%s",s1[i]+1);
		for(int i=1;i<=n;i++)
			for(int j=1;j<=m;j++)
		{
			int x = s1[i][j]-'0';
			suan(i,j,x);
		}
		int ans = 1e9; 
		for(int i=1;i<=n;i++)
			for(int j=1;j<=m;j++)
				for(int k=i+4;k<=n;k++)
					for(int u=j+3;u<=m;u++)
		{
			int sum = -he(i+1,j,k-1,j)-he(i,j+1,i,u-1)+he(i+1,j+1,k-1,u-1)-he(i+1,u,k-1,u)-he(k,j+1,k,u-1);
			sum+=(k-i-1)*2+(u-j-1)*2;
			int tem = sum + he(i+1,u,k-1,u) - (k - i - 1);
			if(tem>=ans)break;
			ans=min(ans,sum);
		}
		cout<<ans<<endl;
	}
}


Comments

Submit
0 Comments
More Questions

1593A - Elections
1607A - Linear Keyboard
EQUALCOIN Equal Coins
XOREQN Xor Equation
MAKEPAL Weird Palindrome Making
HILLSEQ Hill Sequence
MAXBRIDGE Maximise the bridges
WLDRPL Wildcard Replacement
1221. Split a String in Balanced Strings
1002. Find Common Characters
1602A - Two Subsequences
1555A - PizzaForces
1607B - Odd Grasshopper
1084A - The Fair Nut and Elevator
1440B - Sum of Medians
1032A - Kitchen Utensils
1501B - Napoleon Cake
1584B - Coloring Rectangles
1562B - Scenes From a Memory
1521A - Nastia and Nearly Good Numbers
208. Implement Trie
1605B - Reverse Sort
1607C - Minimum Extraction
1604B - XOR Specia-LIS-t
1606B - Update Files
1598B - Groups
1602B - Divine Array
1594B - Special Numbers
1614A - Divan and a Store
2085. Count Common Words With One Occurrence