邻居和新年晚会

时间:2019-05-16 05:15:08

标签: python-3.x algorithm

我能够通过示例测试案例,但是提交后我的解决方案失败了。 有人可以告诉我我要去哪里吗?

问题:

在XYZ社会中,邻居们彼此讨厌对方的态度。在社会上为迎接新年组织了各种活动。门票提供给每个房屋,上面写有整数。有些票证带有正整数,有些票证带有负整数。晚上,人们不得不将门票带到俱乐部俱乐部,合格的俱乐部成员将获得令人兴奋的礼物。赢得礼物的资格取决于最大数目,该数目可以由票数形成,同时要记住邻居彼此讨厌。由于邻居彼此讨厌,因此在最大和列表中两者不能在一起。

社会的主席辛格先生是一个明智的人,他知道社会中的邻居彼此不喜欢。另外,他也不想在别人面前变坏。因此,他想到了一个设计程序的想法,该程序将提供构成最大和的整数列表,因此该列表的所有成员都将获得礼物。这个想法的唯一问题是他不懂编程,所以他要你提供正确的整数列表。人们可能很烦人,但很聪明,如果您提供的清单没有达到最大数目,他们会战斗。

  

注意:写在个人机票上的整数可能是也可能不是   独特。如果有两个列表的最大和相等,则   第一个更大的元素的列表将被考虑。为更好的   理解,请查看样本测试中测试案例4的说明   案件。整数为0的彩票不被视为中奖   礼物。

输入格式 输入的第一行包括测试用例的数量T。

每个测试用例的第一行包括社会上的房屋数量(售票数量)N。

每个测试用例的第二行包括N个空格分隔的票证,上面写有整数。

约束

  • 1 <= T <= 10
  • 1 <= N <= 10000
  • -1000 <= Integer_on_Ticket <= 1000
  

输出格式对于每个测试用例,将票证编号打印在一个纸中   形成最大和的行,格式类似于“样本测试”   情况。

TestCase 1示例

  

输入

5

5

-1 7 8 -5 4

4

3 2 1 -1

4

11 12 -2 -1

4

4 5 4 3

4

5 10 4 -1

输出

48

13

12

44

10

我的解决方案:

x=int(input(''))
for i in range(0,x):
    y=int(input(''))        
    s=input('')
    houses=s.split()
    houses1=[int(item) for item in houses]
    Nhouses=[]
    even=[]
    odd=[]
    final=[]
    final1=[]
    for p in range(0,len(houses1)):
        if p%2==0:
            even.append(houses1[p])
        else:
            odd.append(houses1[p])

    for i in houses1:
        if i<0:
            Nhouses.append(i)

    if houses1==Nhouses:
        maxi=max(Nhouses)
        print(maxi)
    else:
        sum_even=0
        sum_odd=0

        for i in even:
            if i>0:
                sum_even+=i
                final.append(i)

        for i in odd:
            if i>0:
                sum_odd+=i
                final1.append(i)

        final.reverse()
        final1.reverse()
        final2=[]
        if sum_even>sum_odd:
            for j in final:
                print(j,end="")
        elif sum_odd>sum_even:
            for j in final1:
                print(j,end="")
        else:
            for i,j in zip(final,final1):
                if i>j:
                    final2=final
                    break
                else:
                    final2=final1
            for j in final2:
                print(j,end="")
        print()

6 个答案:

答案 0 :(得分:1)

这是基于Kadane算法的标准DP问题。

考虑这个-

// Constant space DP-solution to calculate maximum sum in the given
// array with no adjacent elements considered
int maxSumSubseq(int arr[], int n)
{
    // base case
    if (n == 1)
        return arr[0];

    // store maximum sum till index i-2
    int prev_prev = arr[0];

    // stores maximum sum till index i-1
    int prev = max(arr[0], arr[1]);

    // start from index 2
    for (int i = 2; i < n; i++)
    {
        // curr stores the maximum sum till index i
        int curr = max(arr[i], max(prev, prev_prev + arr[i]));
        prev_prev = prev;
        prev = curr;

    }
    // return maximum sum
    return prev;
}

此外,我建议您等待比赛结束,然后您将自动获得答案。

答案 1 :(得分:0)

我能够从数组中获得最大和:

public static int getMaximumValue(int[] neighbour) {

        int incl = neighbour[0];
        int excl = 0; 
        int excl_new; 

        for (int i = 1; i < neighbour.length; i++) {
            excl_new = (incl > excl) ? incl : excl;
            incl = excl + neighbour[i];
            excl = excl_new;
        }
       return ((incl > excl) ? incl : excl);
    }

答案 2 :(得分:0)

这是一个解决方案:

def get_pair(t, N):
    if len(t) == 0:
        return

    s = None
    cor = []

    for i in range(N):
        for j in range(N):
            if i == j or abs(i - j) == 1 or t[i] == 0 or t[j] == 0:
                continue
            if s == None or t[i] + t[j] > s:
                s = t[i] + t[j]
                cor.append(t[i])
                cor.append(t[j])

    for i in t:
        if i > s:
            return [i]

    return cor




def main():
    T = int(input())
    while T>0:
        N = int(input())
        t = input()
        t = t.split()
        t = [int(i) for i in t]

        l = get_pair(t, N)
        if len(l) == 1:
        print(l[0])
        else:
            s = str(l[-1])+str(l[-2])
            print(s)

    T = T - 1

main()

答案 3 :(得分:0)

公共类testrun {

private static ArrayList<Integer> result = new ArrayList<>();
private static Scanner sc = new Scanner(System.in);
private static ArrayList<Integer> var1 = new ArrayList<>();
private static ArrayList<Integer> var2 = new ArrayList<>();

public static void main(String[] args) {
    int testCase = sc.nextInt();
    if ((testCase <= 10) && (testCase >= 1)) {
        for (int k = 0; k < testCase; k++) {
            boolean goback=false;
            int arrMax = 0;
            int n = sc.nextInt();
            sc.nextLine();
            if ((n <= 10000) && (1 <= n)) {
                String val = sc.nextLine();
                String[] ap = val.split(" ");
                boolean dontLoop = false;
                int[] a = new int[n];
                for (int i = 0; i < ap.length; i++) {
                    a[i] = Integer.parseInt(ap[i]);
                    if (arrMax < a[i]) {
                        arrMax = a[i];
                    }
                    if ((1000 <= a[i]) && (a[i] <= -1000)) {
                        dontLoop = true;

                    }
                }
                int b = 0, count = 0, z = 0;
                boolean remove = false, zeroValue = false, zz1 = false, zz2 = false, ec = false;
                if (dontLoop) {

                } else {
                    goback=true;
                    for (int i = 0; i < a.length; i++) {
                        for (int j = 0; j < a.length; j++) {
                            if ((a[i] == a[j]) && (i == j)) {
                                if (count == 0) {
                                    j++;
                                } else {
                                    int temp = count - 1;
                                    if (result.size() > temp) {
                                        result.remove(temp);
                                        count--;
                                        remove = true;
                                        if (remove) {
                                            if (var1.size() > count - 1) {
                                                var1.remove(count);
                                                var2.remove(count);
                                            }
                                        }
                                    }
                                    j++;
                                }
                            } else {
                                b = a[i] + a[j];
                                result.add(b);
                                count++;
                                var1.add(a[i]);
                                var2.add(a[j]);
                            }
                        }
                    }

                    int max = Collections.max(result);
                    if (max < arrMax) {
                        ec = true;
                    }
                    for (int i = 0; i < a.length; i++) {
                        result.add(a[i]);
                        if (a[i] == 0) {
                            zeroValue = true;
                        }
                    }
                    int index = result.indexOf(Collections.max(result));
                    if (zeroValue) {
                        if (var2.get(index) == 0) {
                            zz1 = true;
                        } else if (var1.get(index) == 0) {
                            zz2 = true;
                        }
                    }
                    if (ec) {
                        System.out.println(result.get(index));
                    } else {
                        String s1 = Integer.toString(var1.get(index));
                        String s2 = Integer.toString(var2.get(index));
                        if (zz1) {
                            System.out.println(s1);
                        } else if (zz2) {
                            System.out.println(s2);
                        } else {
                            String s = s1 + s2;
                            StringBuilder sb = new StringBuilder(s);
                            sb.reverse();
                            System.out.println(sb);
                        }
                    }

                    result.clear();
                    var1.clear();
                    var2.clear();
                }
                if (!goback){
                break;}
            } else {
                if (!goback){
                break;}
            }
        }
    }
}

}

答案 4 :(得分:0)

/ *程序遵循二进制搜索算法* /

#include <stdio.h>
#include    <stdlib.h>
#include    <stdbool.h>
#include    <string.h>
// function to return sum of elements 
// in an array of size n 
int sum(int arr[], int n) 
{ 
    int sum = 0; // initialize sum 

    // Iterate through all elements  
    // and add them to sum 
    for (int i = 0; i < n; i++) 
    sum += arr[i]; 

    return sum; 
} 



bool inc_byte_binary(unsigned int *binaryStream,int n)                  // Binary increment in byte
{
    unsigned int carry = 1;
    for(int i=0;i<n;i++)
    {
        binaryStream[i] = binaryStream[i]^carry ;
        carry = binaryStream[i]&carry   ;
        //printf("%d ",binaryStream[i]);

    }
    if(sum((int*)binaryStream,n)==0)
        return false;
    else
        return true;

}




 bool isNeighbourMatch(unsigned int *binaryStream,int b_n)          // match binary in neighbour
 {
     int n = b_n*sizeof(int)*8;
     int p_i= n;
     int i;
     for(i=0;i<n;i++)
        {
            if(binaryStream[i]==1)
            {
                if(i == p_i+1)
                    break;
                else
                    p_i=i;
            }

        }
        if(i<n)
            return true;
        else
            return false;
 }
 bool get_nextnn_bin(unsigned int *binaryStream,int b_n)        //next binary with neighbour not match
 {
    int i;
   // return false;
     do
     {
        if(inc_byte_binary(binaryStream,b_n)==false)
            break;

     }while( isNeighbourMatch(binaryStream, b_n));

     if(sum((int*)binaryStream,b_n)>0)
        return true;
    else
        return false;
 }
 int sum_by_bin(int *ticket,unsigned int *binaryStream,int n){      // sum of one in the binary of ticket


     int sum=0;
     for(int i=0;i<n;i++)
        {
            if(binaryStream[i]==1)
            {
                    sum+=ticket[i];

            }

        }
        return sum;

 }
bool validate_zero_in_stream(int *ticket,unsigned int *binaryStream,int n)  // Validate good sequency, if it not have zero
{
   //int n = b_n*sizeof(int);
    int i;
     for( i=0;i<n;i++)
        {
            if(binaryStream[i]==1)
            {
                if(ticket[i]==0)
                    break;
            }

        }
        if(i<n)
            return true;
        else 
            return false;
}
 int next_positive(unsigned int *binaryStream, int r_bin)         // move downgrade
{
    do
    {
    r_bin--;
    } while(r_bin>=0 && binaryStream[r_bin]==0);
    return r_bin;
}
void print_bin(unsigned int *binaryStream,int n)    // print the binar seq
{
    //int n = b_n*sizeof(int);

    for(int i=n;i>0;i--)
    {

        printf("%d",binaryStream[i-1]);
    }
}
void print_ticket(int *ticket,unsigned int *binaryStream,int n) // print the ticket based on binary seq
{
    //int n = b_n*sizeof(int);

    for(int i=n;i>0;i--)
    {
       if(binaryStream[i-1]==1)
       { 
        //printf("%d",binaryStream[i-1]);
        printf("%d",ticket[i-1]);
       }
    }
}
int main(int argc, char *a[])
{
    int t,n,p_n,r_n;

    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
    int *ticket = (int*)malloc(n*sizeof(int));
    for(int i=0;i<n;i++)
        scanf("%d",&ticket[i]);

    unsigned int *binaryStream = (unsigned int*)calloc(sizeof(int),n);
    unsigned int *r_binaryStream = (unsigned int*)calloc(sizeof(int),n);

// Apply binary search algorithm
    while(get_nextnn_bin(binaryStream,n)==true)
    {


       if(validate_zero_in_stream(ticket,binaryStream,n) == false)
        {

            if(sum_by_bin(ticket,binaryStream,n) > sum_by_bin(ticket,r_binaryStream,n))

               memcpy(r_binaryStream,binaryStream,n*sizeof(int)) ;

            else if(sum_by_bin(ticket,binaryStream,n) == sum_by_bin(ticket,r_binaryStream,n))
            {

                int r_i =n,c_i=n;
                while(r_i>=0 && c_i>0)
                {
                    r_i = next_positive(r_binaryStream,r_i);
                    c_i = next_positive(binaryStream,c_i);
                    if(r_i>=0 && c_i>=0)
                    {
                        if(ticket[c_i]>ticket[r_i])
                        {
                            memcpy(r_binaryStream,binaryStream,n*sizeof(int));
                            break;
                        }
                    }else
                        break;

                }
            }
        }  


    }
    print_ticket(ticket,r_binaryStream,n); 

    }

    return 0;
}

答案 5 :(得分:0)

没有相邻元素的最大和是DP中的一个标准问题,但更有趣的是,列表中被跟踪元素的逆序构成了最大和。

跟踪元素是我们需要做的。以下算法是 O(N)实现。

import java.util.ArrayList;
import java.util.Scanner;

public class Solution {

private static String getReverse(ArrayList<Integer> maxList) {
    String reverse = "";
    for (Integer i : maxList) {
        if (i != 0) {
            reverse = i + reverse;
        }
    }
    return reverse;
}

private static String findTicketOrderForMaxSum(int[] tickets) {
    int excludingNeighbours = 0;
    ArrayList<Integer> excludingMaxSumList = new ArrayList<>();

    int includingNeighbours = tickets[0];
    ArrayList<Integer> maxSumIndicesList = new ArrayList<>();
    maxSumIndicesList.add(0);

    for (int i = 1; i < tickets.length; i++) {
        final int currentBestIncludingNeighbours;
        final ArrayList<Integer> currentBestSumList;
        if (excludingNeighbours > 0) {
            currentBestIncludingNeighbours = excludingNeighbours + tickets[i];
            currentBestSumList = new ArrayList<>(excludingMaxSumList);
        } else {
            currentBestIncludingNeighbours = tickets[i];
            currentBestSumList = new ArrayList<>();
        }
        currentBestSumList.add(i);

        excludingNeighbours = includingNeighbours;
        excludingMaxSumList = new ArrayList<>(maxSumIndicesList);

        if (currentBestIncludingNeighbours > includingNeighbours) {
            includingNeighbours = currentBestIncludingNeighbours;
            maxSumIndicesList = currentBestSumList;
        }
    }
    ArrayList<Integer> elements = new ArrayList<>();
    for(Integer i: maxSumIndicesList){
        elements.add(tickets[i]);
    }
    return getReverse(elements);
}

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int testCases = in.nextInt();
    while (testCases > 0) {
        int houseTickets = in.nextInt();
        int[] tickets = new int[houseTickets];

        for (int i = 0; i < houseTickets; i++) {
            tickets[i] = in.nextInt();
        }

        String ticketOrder = findTicketOrderForMaxSum(tickets);
        System.out.println(ticketOrder);

        testCases--;
    }
}
}

我想说求和的解决方案是对 Kadane算法的略微修改,同时跟踪通过在迭代时排除/包含给定索引的元素可以达到的最佳和。