Saturday, September 14, 2013

UVA 11553 :: GRID


Going through all permutation as test input is small. this is JAVA solution. its time limit exceeds , you will get accept in C++ use next_permutation function. this code is nice to see how actual permutation would be designed.

import java.util.Scanner;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author piyush
*/
public class Main {
static int grid[][]=new int[10][10];
static int n;
static int min=10000000;
public static void main(String args[])
{
int a[]=new int[20];
Scanner sc = new Scanner(System.in);
int T=sc.nextInt();
while(0!=T--)
{
n=sc.nextInt();
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
grid[i][j]=sc.nextInt();
}
}
for(int i=0;i<n;i++)
{
a[i]=i;
}
min=10000000;
permu(0,a,n);
System.out.println(min);
}
}
public static void permu(int a,int arr[],int n)
{
if(a==n-1)
{
int sum=0;
for(int i=0;i<n;i++)
{
sum=sum+grid[i][arr[i]];
System.out.print(arr[i]+" ");
}
System.out.println();
if(sum<min)min=sum;
return ;
}
else
{
for(int j=a;j<n;j++)
{
int temp=arr[j]; arr[j]=arr[a]; arr[a]=temp;
permu(a+1,arr,n);
temp=arr[j]; arr[j]=arr[a]; arr[a]=temp;
}
}
}
}
view raw gistfile1.txt hosted with ❤ by GitHub

1 comment:

  1. Nice article buddy, proved very helpful. People who want tips on GATE exam preparation can also check this blog out https://www.kreatryx.com/blog/strategy-gate-2017-nadeesh-aggarwal-air-21-gate-2016-ee/ Best of luck.

    ReplyDelete