1334C. Circle of Monsters - Codeforces Solution C++

  Problem Link : 1334C. Circle of Monsters 


✅ C++ Solution :

 
#include<bits/stdc++.h>
using namespace std;

#define ll long long int

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	int t;
	cin>>t;
	while(t--)
	{
		int n;
		cin>>n;
		ll arr[n][2];
		for(int i=0;i<n;i++)
			cin>>arr[i][0]>>arr[i][1];
		if(n==1)
		{
			cout<<arr[0][0]<<"\n";
			continue;
		}
		ll ans,curr=0,prev=0;
		for(int i=0;i<n;i++)
		{
			if(arr[i][0] > prev)
				curr+=arr[i][0]-prev;
			prev=arr[i][1];
		}
		ans=curr;
		prev=curr;
		for(int i=1;i<n;i++)
		{
			curr=prev-arr[i-1][0];
			if(arr[i][0] > arr[i-1][1])
				curr+=arr[i-1][1];
			else
				curr+=arr[i][0];
			if(arr[(i+n-1)%n][0] > arr[(i+n-2)%n][1])
				curr+=arr[(i+n-1)%n][0] - arr[(i+n-2)%n][1];
			ans=min(ans,curr);
			prev=curr;
		}
		cout<<ans<<"\n";
	}
}

 

Thank you for your patience reading. If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Whatsapp or Facebook. 

😇Happy Learning!!