MaxEdges CodeChef Solution

Problem – MaxEdges CodeChef Solution

This website is dedicated for CodeChef solution where we will publish right solution of all your favourite CodeChef problems along with detailed explanatory of different competitive programming concepts and languages.
<<Previous CodeChef Problem Next Codechef Problem>>

MaxEdges CodeChef Solution in C++17

#include <bits/stdc++.h>
using namespace std;
namespace fastIO{
	#define BUF_SIZE 100000
	#define OUT_SIZE 100000
	//fread->read
	bool IOerror=0;
	//inline char nc(){char ch=getchar();if(ch==-1)IOerror=1;return ch;} 
	inline char nc(){
		static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE;
		if(p1==pend){
			p1=buf;pend=buf+fread(buf,1,BUF_SIZE,stdin);
			if(pend==p1){IOerror=1;return -1;}
		}
		return *p1++;
	}
	inline bool blank(char ch){return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';}
	template<class T> inline bool read(T &x){
		bool sign=0;char ch=nc();x=0;
		for(;blank(ch);ch=nc());
		if(IOerror)return false;
		if(ch=='-')sign=1,ch=nc();
		for(;ch>='0'&&ch<='9';ch=nc())x=x*10+ch-'0';
		if(sign)x=-x;
		return true;
	}
	inline bool read(double &x){
		bool sign=0;char ch=nc();x=0;
		for(;blank(ch);ch=nc());
		if(IOerror)return false;
		if(ch=='-')sign=1,ch=nc();
		for(;ch>='0'&&ch<='9';ch=nc())x=x*10+ch-'0';
		if(ch=='.'){
			double tmp=1; ch=nc();
			for(;ch>='0'&&ch<='9';ch=nc())tmp/=10.0,x+=tmp*(ch-'0');
		}
		if(sign)x=-x;
		return true;
	}
	inline bool read(char *s){
		char ch=nc();
		for(;blank(ch);ch=nc());
		if(IOerror)return false;
		for(;!blank(ch)&&!IOerror;ch=nc())*s++=ch;
		*s=0;
		return true;
	}
	inline bool read_line(char *s){
		char ch=nc();
		for(;blank(ch);ch=nc());
		if(IOerror)return false;
		for(;ch!='\n'&&!IOerror;ch=nc())*s++=ch;
		*s=0;
		return true;
	}
	inline bool read(char &c){
		for(c=nc();blank(c);c=nc());
		if(IOerror){c=-1;return false;}
		return true; 
	}
	template<class T,class... U>bool read(T& h,U&... t){return read(h)&&read(t...);}
	#undef OUT_SIZE
	#undef BUF_SIZE
};
using namespace fastIO;
/************* debug begin *************/
string to_string(string s){return '"'+s+'"';}
string to_string(const char* s){return to_string((string)s);}
string to_string(const bool& b){return(b?"true":"false");}
template<class T>string to_string(T x){ostringstream sout;sout<<x;return sout.str();}
template<class A,class B>string to_string(pair<A,B> p){return "("+to_string(p.first)+", "+to_string(p.second)+")";}
template<class A>string to_string(const vector<A> v){
	int f=1;string res="{";for(const auto x:v){if(!f)res+= ", ";f=0;res+=to_string(x);}res+="}";
	return res;
}
void debug_out(){puts("");}
template<class T,class... U>void debug_out(const T& h,const U&... t){cout<<" "<<to_string(h);debug_out(t...);}
#ifdef tokitsukaze 
#define debug(...) cout<<"["<<#__VA_ARGS__<<"]:",debug_out(__VA_ARGS__);
#else
#define debug(...) 233;
#endif
/*************  debug end  *************/
#define mem(a,b) memset((a),(b),sizeof(a))
#define MP make_pair
#define pb push_back
#define fi first
#define se second
#define sz(x) (int)x.size()
#define all(x) x.begin(),x.end()
#define sqr(x) (x)*(x)
using namespace __gnu_cxx;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
typedef pair<ll,ll> PLL;
typedef pair<int,ll> PIL;
typedef pair<ll,int> PLI;
typedef vector<int> VI;
typedef vector<ll> VL;
typedef vector<PII > VPII;
/************* define end  *************/
void read(int *x,int l,int r){for(int i=l;i<=r;i++) read(x[i]);}
void read(ll *x,int l,int r){for(int i=l;i<=r;i++) read(x[i]);}
void read(double *x,int l,int r){for(int i=l;i<=r;i++) read(x[i]);}
void println(VI x){for(int i=0;i<sz(x);i++) printf("%d%c",x[i]," \n"[i==sz(x)-1]);}
void println(VL x){for(int i=0;i<sz(x);i++) printf("%lld%c",x[i]," \n"[i==sz(x)-1]);}
void println(int *x,int l,int r){for(int i=l;i<=r;i++) printf("%d%c",x[i]," \n"[i==r]);}
void println(ll *x,int l,int r){for(int i=l;i<=r;i++) printf("%lld%c",x[i]," \n"[i==r]);}
/*************** IO end  ***************/
void go();
int main(){
	#ifdef tokitsukaze
		freopen("TEST.txt","r",stdin);
	#endif
	go();return 0;
}
const int INF=0x3f3f3f3f;
const ll LLINF=0x3f3f3f3f3f3f3f3fLL;
const double PI=acos(-1.0);
const double eps=1e-6;
const int MAX=1e5+10;
const ll mod=1e9+7;
/*********************************  head  *********************************/
void go()
{
	int t,n;
	ll a,b,tmp,ans;
	read(t);
	while(t--)
	{
		read(n,a,b);
		if(a+b>n)
		{
			tmp=a+b-n;
			a-=tmp;
			b-=tmp;
			ans=a*b;
		}
		else
		{
			tmp=n-(a+b);
			ans=a*b+tmp*(a+b)+tmp*(tmp-1)/2;
		}
		printf("%lld\n",ans);
	}
}

MaxEdges CodeChef Solution in C++14

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

int main()
{
    int t;
    cin >> t;
    while (t--)
    {
        long long n, l, k;
        cin >> n >> l >> k;
        if (l + k <= n)
        {
           cout << l * k + (n - k - l) * (k + l)+(n-k-l-1)*(n-k-l)/2 << endl;
        }
        else
        {
            cout<<(n-l)*(n-k)<<endl;
        }
    }
    return 0;
}

MaxEdges CodeChef Solution in PYTH 3

# cook your dish here
num_tests = int(input())

for t in range(num_tests):
    lst = [int(x) for x in input().split(' ')]
    nodes,sources,sinks = lst
    source_sinks = max(0,sources + sinks - nodes)
    sources -= source_sinks
    sinks -= source_sinks
    reg = max(nodes - sources - sinks - source_sinks,0)
    
    ans = (reg*(reg-1))//2
    ans += (sources*reg)
    ans += (sinks*reg)
    ans += (sources*sinks)
    
    print(ans)

MaxEdges CodeChef Solution in C

#include <stdio.h>

int main(void) {
	// your code goes here
	int t;
	scanf("%d",&t);
	while(t--)
	{
	    long long int n,k,l;
	    long long int ct;
	    scanf("%lld%lld%lld",&n,&k,&l);
	    long long int i;
	    i=n-(k+l);
	    if(i<0)
	    {
	        i=abs(i);
	        k-=i;
	        l-=i;
	        i=0;
	    }
	    ct=k*(i+l)+i*(i-1)/2+i*l;
	   
	    printf("%lld\n",ct);
	    
	    
	}
	return 0;
}

MaxEdges CodeChef Solution in JAVA

import java.io.*;
import java.util.*;

public class Main {

    static class Reader
    {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader()
        {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }
        public String readLine() throws IOException
        {
            byte[] buf = new byte[1000001]; // line length
            int cnt = 0, c;
            while((c = read()) <= ' '){}
            do{
                if (c == 13 || c == 10)
                    break;
                buf[cnt++] = (byte) c;
            }while ((c = read()) != -1);
            return new String(buf, 0, cnt);
        }
        public String next() throws IOException
        {
            byte[] buf = new byte[1000001]; // line length
            int cnt = 0, c;
            while((c = read()) <= ' '){}
            do{
                buf[cnt++] = (byte) c;
            }while ((c = read()) != -1 && c > ' ');
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException
        {
            int ret = 0;
            byte c = read();
            while (c <= ' '){c = read();}
            boolean neg = (c == '-');
            if (neg)c = read();
            do
            {
                ret = ret * 10 + c - '0';
            }  while ((c = read()) >= '0' && c <= '9');

            if (neg) return -ret;
            return ret;
        }

        public long nextLong() throws IOException
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }

        public double nextDouble() throws IOException
        {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();

            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');

            if (c == '.')
            {
                while ((c = read()) >= '0' && c <= '9')
                {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg)
                return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException
        {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }

        private byte read() throws IOException
        {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException
        {
            if (din == null)
                return;
            din.close();
        }
    }
    public static void print(int[] arr){
        for(int i = 0 ;i<arr.length;i++){
            System.out.print((arr[i])+" ");
        }
        System.out.println("");
    }
    public static void print(int[][] arr){
        for(int i = 0 ;i<arr.length;i++) {
            for (int j = 0; j < arr[0].length; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println("");
        }
    }
    public static void print(ArrayList<Integer> arr){
        for(int i:arr){
            System.out.print(i+" ");
        }
        System.out.println("");
    }


    public static void main(String[] args) throws IOException{
        Reader sc = new Reader();
        PrintStream ps = new PrintStream(System.out);
        int tc = sc.nextInt();
        while( tc-- > 0){
            long N = sc.nextLong();
            long source = sc.nextLong();
            long sink = sc.nextLong();
            
            long internalNodes = N - source - sink;
            if(internalNodes < 0){
                source += internalNodes;
                sink += internalNodes;
                internalNodes = 0;
            }
            
            long ans = (source*(internalNodes + sink)) + (internalNodes*sink) + ((internalNodes*(internalNodes - 1))/2);
            ps.println(ans);
            //tc--;
        }
    }
}

MaxEdges CodeChef Solution in PYPY 3

import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#######################################
# #######
  #     #
  #######
  #   #
  #    #
  #      #   Rahul Kaushik.2.0 #

for i in range(int(input())):
    n,k,l=map(int,input().split())
    if k+l>=n:
        x=k+l-n
        n-=x
        k-=x
        l-=x
        print(k*l)
    else:
        x=n-(k+l)
        print(k*l+x*(k+l)+((x-1)*x)//2)
    
    

MaxEdges CodeChef Solution in PYTH

t=int(input())
for _ in range(t):
    n,k,l=list(map(int,raw_input().split()));
    n=n-(l+k);
    # print(n)
    if n<0:
        n=n*-1;
        l=l-n;
        k=k-n;
        n=0;
    a=long()
    a=(k*(n+l))+(n*l)+(n*(n-1)/2)
    print((a))

MaxEdges CodeChef Solution in C#

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;

public class Test
{
	   private static int _mod = (int)1e9 + 7;

        public static void Main(string[] args)
        {
            //Precompute();
            int t = GetInt();
            for (int i = 0; i < t; i++)
                Solve();
        }

        public static void Solve()
        {
            var a = GetLongArray();
            long n = a[0];
            long sources = a[1];
            long sinks = a[2];
            long edges = 0;
            if(sources +sinks <= n)
            {
                long middle = n -sinks - sources;
                edges = sources * middle + middle * sinks + sources * sinks
                        + middle * (middle -1) / 2;
            }
            else
            {
                long areBoth = sources + sinks - n;
                sources -= areBoth;
                sinks -= areBoth;
                edges = sources * sinks;
            }
#if DEBUG
            Console.Write("The answer is     ---------> ");
#endif
            Console.WriteLine(edges);
        }

        public static int GetInt() => int.Parse(Console.ReadLine());
        public static long GetLong() => long.Parse(Console.ReadLine());

        public static int[] GetIntArray() => Console.ReadLine().Trim().Split(' ').Select(int.Parse).ToArray();
        public static long[] GetLongArray() => Console.ReadLine().Trim().Split(' ').Select(long.Parse).ToArray();
        public static double[] GetDoublesArray() => Console.ReadLine().Trim().Split(' ').Select(d => Convert.ToDouble(d, CultureInfo.InvariantCulture)).ToArray();

        public static long Gcd(long a, long b) => b == 0 ? a : Gcd(b, a % b);
}

MaxEdges CodeChef Solution in NODEJS

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const [n, src, dst] = lines[l++].trim().split(' ').map(BigInt)
        output[i] = solve(n, src, dst)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, src, dst) {
    let both, neither
    if (src + dst >= n) {
        both = src + dst - n
        neither = 0n
        return (src - both) * (dst - both)
    } else {
        both = 0n
        neither = n - (src + dst)
        return src * dst + (src + dst) * neither + neither * (neither - 1n) / 2n
    }
}

MaxEdges CodeChef Solution in GO

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
)

func main() {
	reader := bufio.NewReader(os.Stdin)

	var buf bytes.Buffer

	tc := readNum(reader)

	for tc > 0 {
		tc--
		n, k, l := readThreeNums(reader)
		res := solve(n, k, l)
		buf.WriteString(fmt.Sprintf("%d\n", res))
	}

	fmt.Print(buf.String())
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readString(reader *bufio.Reader) string {
	s, _ := reader.ReadString('\n')
	for i := 0; i < len(s); i++ {
		if s[i] == '\n' || s[i] == '\r' {
			return s[:i]
		}
	}
	return s
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func solve(n int, k int, l int) int64 {
	// a + b + c  <= n
	// where a is source, b is sink, and c both single point
	// a + c = k
	// b + c = l
	if k+l > n {
		y := k + l - n
		return solve(n-y, k-y, l-y)
	}

	// k + l <= n
	// x internal nodes
	x := n - (k + l)
	res := int64(k) * int64(n-k)
	res += int64(x) * int64(l)
	res += int64(x) * int64(x-1) / 2
	return res
}
MaxEdges CodeChef Solution Review:

In our experience, we suggest you solve this MaxEdges CodeChef Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the MaxEdges CodeChef Solution.

Find on CodeChef

Conclusion:

I hope this MaxEdges CodeChef Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Programming Language in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

Cognitive Class Answer

CodeChef Solution

Microsoft Learn

Leave a Reply

Your email address will not be published. Required fields are marked *