1272B - Snow Walking Robot - CodeForces Solution


constructive algorithms greedy implementation *1200

Please click on ads to support us..

Python Code:

for _ in[0]*int(input()):
 u,v,*x=map(input().count,'LRUD');a=min(u,v);b=min(x)
 if b<1:a=a and 1
 elif a<1:b=1
 print(2*(a+b),'L'*a+'U'*b+'R'*a+'D'*b)

C++ Code:

/***from dust i have come, dust i will be***/

#include<bits/stdc++.h>

typedef long long int ll;
typedef unsigned long long int ull;

#define dbg printf("in\n")
#define nl printf("\n");
#define N 210101
#define inf 1e9

#define sf(n) scanf("%d", &n)
#define sff(n,m) scanf("%d%d",&n,&m)
#define sfl(n) scanf("%I64d", &n)
#define sffl(n,m) scanf("%I64d%I64d",&n,&m)

#define pf(n) printf("%d",n)
#define pff(n,m) printf("%d %d",n,m)
#define pffl(n,m) printf("%I64d %I64d",n,m)
#define pfl(n) printf("%I64d",n)
#define pfs(s) printf("%s",s)

#define pb push_back
#define pp pair<int, int>

using namespace std;

int main()
{
    // freopen("in.txt", "r", stdin);

    int i, j, k;
    int n, m, t;
    int u, d, l, r;
    string s;

    sf(t);
    while(t--)
    {
        cin >> s;

        n = s.length();
        u = d = l = r = 0;

        for(i = 0; i < n; i++)
        {
            if(s[i] == 'U')
                u++;
            else if(s[i] == 'D')
                d++;
            else if(s[i] == 'L')
                l++;
            else
                r++;
        }

        m = min(u, d);
        u = d = m;

        m = min(l, r);
        l = r = m;

        string ans = "";

        // after some u / d there must be some l / r and vice versa
        if(u && l && r && d)
        {
            while(u--)
                ans.pb('U');
            while(r--)
                ans.pb('R');
            while(d--)
                ans.pb('D');
            while(l--)
                ans.pb('L');
        }

        else
        {
            if(r && l)
                ans = "LR";
            else if(u && d)
                ans = "UD";
        }

        pf(ans.length());
        nl;
        cout << ans << endl;
    }

    return 0;
}


Comments

Submit
0 Comments
More Questions

470. Implement Rand10() Using Rand7()
866. Prime Palindrome
1516A - Tit for Tat
622. Design Circular Queue
814. Binary Tree Pruning
791. Custom Sort String
787. Cheapest Flights Within K Stops
779. K-th Symbol in Grammar
701. Insert into a Binary Search Tree
429. N-ary Tree Level Order Traversal
739. Daily Temperatures
647. Palindromic Substrings
583. Delete Operation for Two Strings
518. Coin Change 2
516. Longest Palindromic Subsequence
468. Validate IP Address
450. Delete Node in a BST
445. Add Two Numbers II
442. Find All Duplicates in an Array
437. Path Sum III
436. Find Right Interval
435. Non-overlapping Intervals
406. Queue Reconstruction by Height
380. Insert Delete GetRandom O(1)
332. Reconstruct Itinerary
368. Largest Divisible Subset
377. Combination Sum IV
322. Coin Change
307. Range Sum Query - Mutable
287. Find the Duplicate Number