text:
Countries by Area
Challenge
Given two non negative integers a < b, output all countries, from the below Top 100 Countries, where area is between a and b:  a<= area <= b.
Example
147500,180000   --> uruguay, suriname, tunisia, bangladesh
1200000,1300000 --> peru, chad, niger, angola, mali, south africa
1234567,1256789 --> angola, mali

Top 100 Countries by Area (2017):
russia..........................17098250
canada...........................9984670
united states....................9831510
china............................9562911
brazil...........................8515770
australia........................7741220
india............................3287259
argentina........................2780400
kazakhstan.......................2724902
congo............................2686860
algeria..........................2381740
saudi arabia.....................2149690
mexico...........................1964380
indonesia........................1910931
sudan............................1879358
libya............................1759540
iran.............................1745150
mongolia.........................1564120
peru.............................1285220
chad.............................1284000
niger............................1267000
angola...........................1246700
mali.............................1240190
south africa.....................1219090
colombia.........................1141749
ethiopia.........................1104300
bolivia..........................1098580
mauritania.......................1030700
egypt............................1001450
tanzania..........................947300
nigeria...........................923770
venezuela.........................912050
namibia...........................824290
mozambique........................799380
pakistan..........................796100
turkey............................785350
chile.............................756096
zambia............................752610
myanmar...........................676590
afghanistan.......................652860
south sudan.......................644330
somalia...........................637660
central african republic..........622980
ukraine...........................603550
madagascar........................587295
botswana..........................581730
kenya.............................580370
france............................549087
yemen.............................527970
thailand..........................513120
spain.............................505940
turkmenistan......................488100
cameroon..........................475440
papua new guinea..................462840
sweden............................447420
uzbekistan........................447400
morocco...........................446550
iraq..............................435050
greenland.........................410450
paraguay..........................406752
zimbabwe..........................390760
norway............................385178
japan.............................377962
germany...........................357380
finland...........................338420
vietnam...........................330967
malaysia..........................330800
cote d'ivoire.....................322460
poland............................312680
oman..............................309500
italy.............................301340
philippines.......................300000
burkina faso......................274220
new zealand.......................267710
gabon.............................267670
ecuador...........................256370
guinea............................245860
united kingdom....................243610
uganda............................241550
ghana.............................238540
romania...........................238390
laos..............................236800
guyana............................214970
belarus...........................207600
kyrgyz............................199949
senegal...........................196710
syria.............................185180
cambodia..........................181040
uruguay...........................176220
suriname..........................163820
tunisia...........................163610
bangladesh........................147630
nepal.............................147180
tajikistan........................141376
greece............................131960
nicaragua.........................130370
north korea.......................120540
malawi............................118480
eritrea...........................117600
benin.............................114760

Names as separate list
russia
canada
united states
china
brazil
australia
india
argentina
kazakhstan
congo
algeria
saudi arabia
mexico
indonesia
sudan
libya
iran
mongolia
peru
chad
niger
angola
mali
south africa
colombia
ethiopia
bolivia
mauritania
egypt
tanzania
nigeria
venezuela
namibia
mozambique
pakistan
turkey
chile
zambia
myanmar
afghanistan
south sudan
somalia
central african republic
ukraine
madagascar
botswana
kenya
france
yemen
thailand
spain
turkmenistan
cameroon
papua new guinea
sweden
uzbekistan
morocco
iraq
greenland
paraguay
zimbabwe
norway
japan
germany
finland
vietnam
malaysia
cote d'ivoire
poland
oman
italy
philippines
burkina faso
new zealand
gabon
ecuador
guinea
united kingdom
uganda
ghana
romania
laos
guyana
belarus
kyrgyz
senegal
syria
cambodia
uruguay
suriname
tunisia
bangladesh
nepal
tajikistan
greece
nicaragua
north korea
malawi
eritrea
benin

Areas as separate lists
17098250
9984670
9831510
9562911
8515770
7741220
3287259
2780400
2724902
2686860
2381740
2149690
1964380
1910931
1879358
1759540
1745150
1564120
1285220
1284000
1267000
1246700
1240190
1219090
1141749
1104300
1098580
1030700
1001450
947300
923770
912050
824290
799380
796100
785350
756096
752610
676590
652860
644330
637660
622980
603550
587295
581730
580370
549087
527970
513120
505940
488100
475440
462840
447420
447400
446550
435050
410450
406752
390760
385178
377962
357380
338420
330967
330800
322460
312680
309500
301340
300000
274220
267710
267670
256370
245860
243610
241550
238540
238390
236800
214970
207600
199949
196710
185180
181040
176220
163820
163610
147630
147180
141376
131960
130370
120540
118480
117600
114760

Rules

The input and output can be given in any convenient format.
The output can be in any case.
No need to handle invalid input values.
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
If possible, please include a link to an on-line testing environment so other people can try out your code!
Standard loopholes are forbidden.
The code is not allowed to import the list from file or internet.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

some comments for the down-votes...

I believe the reason for the down-votes is the fact that this isn't a challenge that is interesting to golf. There are two problems to solve: First, given a country list and a size list, get the names of the countries where the size is between two values. This is solved in ~50 bytes and not very hard to golf. The second problem is compressing the data. But, given that the program needs to know the exact sizes of each country and the exact names of each country, there isn't very much space to compress this.

Does the output need to be in order of size or can it be unsorted?

@Veskah any order

@mdahmoune I feel like this challenge is too "large" for people to want to go through and find clever rules for this long list of countries

@qwr do u think it will be more interesting if for example I reduce the challenge to the top 16 countries for example?

Sorry, got distracted last night before I could follow up on my -1 which was pretty much for the same reasons outlined by @BlackOwlKai; there is little to no room for creative compression or golfing techniques. This may have been better with some reworking and custom scoring as a [tag:code-challenge].

How in the heck are some countries just like, "yeah, our level of uncertainty of our surface area is in the ONE'S PLACE!" Those guys must have some insanely good rulers.

Node.js,  1170  1164 bytes
Takes input as (a)(b).
a=>b=>eval(require('zlib').inflateSync(Buffer.from('eNpFU8uS6jYQ/RVWyUzdU7cwmNeC2d9vSKUybattC9uSkeQh5utzZCbJBij147yaz0qdddBgU1DBKIM8LJwPqdv0Pj85W0uQdha0QbVWJLnZ3sYkDk4nGVCJawcxGjuk2dloBXEO1smomMPM0QW1jJU3ubKE/KlOW472S2iXJyodJMwR7byIEwziI4IfxbG17fLT3Ioz/HI2qdn01rXGj+y3jhS1nsX4gFYqn0k9Nk+lEGdQzYG9smkkekydHew0cSTCJhkWZAhMfm2tfdKN+d1+eRt0NWLJSr6sJipBY93a1mrg0IKbTNkAHx5U97RjJdVDMb2sWlavXgM2yB2jD76uPeZnpd/exYcaJbpMs2wy528xdEqDp45E7iPTeXVPwphSJ3ZduigraII4BtKrWwSVT/GRrRrFSCuRqWHuA8cUtboUZNhIE5im2wSd5mqwNSIdGHIefmbgcTaEkiZb/oIdmcfIRU/Gx7aaDupKTBcy/1Yy+rV8nxV0yubGL+b7nJkqz4eO8YWNzzVPbZcpkSQvJK0PlR/sVy6kzvopo/jBr3AvVi/SORELXpr/dynZiMGkYSaD/M4Jmu0w2GrJJ5jFWGc882Zp1L8tE4gyG7thTBlAhhe5Os+jl6f03SpJQkvLeDl5QW6cYzYwsw3ytEN2wv13jhxJvCk6S+vBQybe5884DTZ94vNnY4ek4e3tL+j79ePN/LgWxx+8lKi/XHr7LE/qsS9LysXuXBK7RMG/Tt51rCNU0Y0ljgozehykRNkxUsehzuCsDc6HEv70mioV+8tr0Y6T1c2jblnGiQui9Si0xKVgV0OISXE5KQ4FzqeAgc/j1OK83eJ4aAnbotyNCBfiETt4lOj2JJIUyuabL3Ei7ZZIzlQoyvFEAI9jmWCLC4auRHsmeOVxMR53Uey8IfrUo9ippZ/UQVqBRPfZCbMtcd9TwZZSiqxh19SUT91F1TnsptDA1S9BI6XZOyusyoU/jgNHm0SPzL5GcSgCilTtcZzuinPn6ciFAEV9arErbjXzLR0OGv2E2He05+z0gEus+dqXHmdnov8/zD/0T+y37+8fV/mt+rgamOv2/R9Hndmv','base64'))+'')

Try it online!
Inflated code
`benin,eritrea,malawi,(…),russia`.split`,`
filter((_, e) =>
  (
    d += 16 + parseInt(
      `47eo,344,so,(…),8ndso`.split`,`[e],
      30
    )
  ) >= a & b >= d,
  d = 0
)

The base (30) and the hardcoded offset (16) were chosen to optimize the compression of the delta values.

I was about to question your choice of base-30 over base-36 but the saw your note at the end just before I posted my comment.

@Shaggy ...And decided to post this one instead. :P

Wolfram Language 68 bytes
I am uncertain whether this satisfies the requirements.
This uses a built-in function named CountryData.  Wolfram Language knows the areas of all the countries in the world, so it's simply a matter of determining those countries in which the area falls within the given interval.
 c=CountryData;Cases[c@"Countries",x_/;(a=c[x,"Area"][[1]])<=#2&&a>=#]&

As soon as I saw this challenge, I knew Mathematica would have a built-in! I even went looking for it myself but, Jebus, Mathematica is fecking huge!

As soon as it’s not an import from a file nor internet, it’s ok +1

Python 3, 1961 1579 1353 bytes
lambda a,b:["india,argentina,kazakhstan,congo,algeria,saudi arabia,mexico,indonesia,sudan,libya,iran,mongolia,peru,chad,niger,angola,mali,south africa,colombia,ethiopia,bolivia,mauritania,egypt,tanzania,nigeria,venezuela,namibia,mozambique,pakistan,turkey,chile,zambia,myanmar,afghanistan,south sudan,somalia,central african republic,ukraine,madagascar,botswana,kenya,france,yemen,thailand,spain,turkmenistan,cameroon,papua new guinea,sweden,uzbekistan,morocco,iraq,greenland,paraguay,zimbabwe,norway,japan,germany,finland,vietnam,malaysia,cote d'ivoire,poland,oman,italy,philippines,burkina faso,new zealand,gabon,ecuador,guinea,united kingdom,uganda,ghana,romania,laos,guyana,belarus,kyrgyz,senegal,syria,cambodia,uruguay,suriname,tunisia,bangladesh,nepal,tajikistan,greece,nicaragua,north korea,malawi,eritrea,benin,russia,canada,united states,china,brazil,australia".split(",")[i]for i in range(100)if a<=int((11*'1'+83*'0'+'a55554ynmlfa64411xrrrqqqonnmlkjjhhhgggeddddccccbbaaaa9999988888777766666'+10*'5'+'4444333333332222226yuo2lglel123yapeiji5pk4goj3gasjo42t74iztocxlgfrbzug6xllkbspd93n933wpmgfvqqh976432lga7yvrii551tsljigh0qyixgdj7rpqh4okvoqmyxnz3oaqxsq0t9zep2r60pp5vtodxdmu487kopui7mr4d8t9tihlkjtpyd2xpv6asvoze8wk3tl0fqj371st5rcq0gm4fe4eskogkqm904k2waqy0waou602s0ar6efucwcoocs6qeogey8kjw8k8kc8eaegyq4yseo56ww0kquc4kec4oseyif6w')[i::100],36)<=b]

Try it online!
-382 bytes thanks to Shaggy
-226 bytes by a new data storage method and some changes by Jonathan Allan

You can drop the space before the join

You could probably save quite a bit by combining each of the arrays into comma-delimited strings and then splitting on comma.

Straight string comparisons of the hex won't work. For example f(17, 18) will yield 'colombia'.

You don't need to format the output with join you can just have a list comprehension. You can probably save with a zip. (BTW if you still go for the hex string approach note that you could remove both [2:] and instead use '0x'+'104e60a ...[i])

Jaysis, 382 bytes?! Didn't think it'd be quite that much!

05AB1E, 845 726 724 bytes
Ÿ•LˆB1?+β»,¦ïp,fpîÃUK„»L`l¢~Rζ₃f(–α9OÌHíÜ$;’*Ê¸šöÏG∞zW¦pƒ;₃øÅ^êà©Q₁¤
cΘ¥₄₃₁¾«ål5ó eù&AŠ×Y‡p3ΓòÔ¬Š|üÛT∊DìaM1Gæ³RùVòí¢ʒʒP,vζšƶ«Ƶ¹”jWL¦¹†Ãн‘ƶËθ±…KãÐΓ¼¿λÎ‹½ª%=KHÛá$çöα=ÍTćÒ¹∞ïkÑ§qγHšÎGêĆ[‹Î½žMcǝEØιœ₆Î»Ô#ζ₆Σγ’Ƶä"‚žlóƒβÀÙlƵ=αн#$½/Y€Š:¹!
ÿFw91?ì3-ŸWuµ\ú‹µú1vPε»ã#º{ǝ¯¼¢vN=тLʒ”T³é¶ùÅγ¬ë‘/ÐžaÕÄ"Õ-Ý–°ǝ-β₆›*ŽBÂ₂₄q••17ò÷•вå.•1d|WÈ!ÝWàÁвZr¦h…ù„D&«r4¡8!’}`U²†ánB;ÂMÒ¤wt\pm≠¤Ëм h6oìIdšÁô1•#„af…a f:„di" d'i":`’ž¦0…¥0ƒŠ ƒ¼0‡¤0£‰0ˆ‚0Š™0²Ð0Û½0Ê›0Þ²0»´ Â¸0Žè0°×0Ïï0ÿ0¨¤0ãì0¾ç0Êä0èå0àÜ0çÐ0ƒÞ ‹…0Â©0×ˆ0ÎÝ0ÿ0¬æ0Ì¹0Äë0Ã£0ÌÚ0Øµ0¬¬0¤•0¸Ž0Ó±0ÜÞ0¹ä0ƒÞ Ïï0ê¢0‡Þ ïŽ •€0·±0Ý£0Êž0¼¤0ˆÖ0àç0§á0•ì0ÿ0å£0âŽ €¢ «á0§…0Ý©0ÊŒ0•°0ˆ¨ˆÑ0ßÚ0ÄÒ0¬ì0Šè0‰Í0²á0°‚0°ˆ0ÿ0¯¬0ß»0í¿0°¦0ÿ0€¢ ™Æ0ÿ0Ìè0«á0ƒŠ Šß0ÑÝ0Ó•0À‹0ìÞ0äß0Öæ0ÿ0ã¼0Ñè0ÍÆ0Õ·0ÿ0Úˆ0Éã0ÄÑ0ÿ0«š0ÚÊ0„¡ ¡è0à›0ÿ0ÿ’0¡sÏ

No smart golfs yet, but will see what I can do later on.
Try it online or verify all test cases.
Explanation:
Ÿ                    # Get the inclusive range of the two (implicit) inputs
 •...•               # Compressed integer 1973189551155729951158047504888550693285038979215196451111846739112857422275219605859797606876792240255951887197422137126381236888252746087204379433177795015673735312875287174369802127043070332938030374559331221793543099653787758410730754595832945510288634919093697357543931716347226050469833259385438225825153429642271254788538576531893907231375001829235576168553954340620130825485946678723358989342130504637082203898949974502648169087327686854812063938661992036699706767699157860904798957505081143747312911246515350313735031397786562111474800728183906801552964415604114267221708014650503416371603814718203653991102167755222616117998692632503630077961754668397032445720874683416593177351139861390338743408903539745973060232
      •17ò÷•         # Compressed integer 17098251
            в        # Convert the large integer to Base-17098251 as list
             å       # Check for each if its in the ranged-list (1 if truthy; 0 if falsey)
.•...•               # Compressed string "benin eritrea tajikistan suriname kyrgyz gabon burkinafaso cotedivoire turkmenistan mauritania libya"
      #              # Split by spaces
       „af…a f:      # Replace "af" with "a f" (for "burkina faso")
       „di" d'i":    # Replace "di" with " d'i'" (for "cote d'ivoire")
                 `   # Push all strings as separated items to the stack
’...’                # Push dictionary string "russia0canada0united states0china0brazil0australia0india0argentina0kazakhstan0congo0algeria0saudi arabia0mexico0indonesia0sudan0ÿ0iran0mongolia0peru0chad0niger0angola0mali0south africa0colombia0ethiopia0bolivia0ÿ0egypt0tanzania0nigeria0venezuela0namibia0mozambique0pakistan0turkey0chile0zambia0myanmar0afghanistan0south sudan0somalia0central african republic0ukraine0madagascar0botswana0kenya0france0yemen0thailand0spain0ÿ0cameroon0papua new guinea0sweden0uzbekistan0morocco0iraq0greenland0paraguay0zimbabwe0norway0japan0germany0finland0vietnam0malaysia0ÿ0poland0oman0italy0philippines0ÿ0new zealand0ÿ0ecuador0guinea0united kingdom0uganda0ghana0romania0laos0guyana0belarus0ÿ0senegal0syria0cambodia0uruguay0ÿ0tunisia0bangladesh0nepal0ÿ0greece0nicaragua0north korea0malawi0ÿ0ÿ",
                     # where the `ÿ` are filled with the strings on the stack to form: "russia0canada0united states0china0brazil0australia0india0argentina0kazakhstan0congo0algeria0saudi arabia0mexico0indonesia0sudan0libya0iran0mongolia0peru0chad0niger0angola0mali0south africa0colombia0ethiopia0bolivia0mauritania0egypt0tanzania0nigeria0venezuela0namibia0mozambique0pakistan0turkey0chile0zambia0myanmar0afghanistan0south sudan0somalia0central african republic0ukraine0madagascar0botswana0kenya0france0yemen0thailand0spain0turkmenistan0cameroon0papua new guinea0sweden0uzbekistan0morocco0iraq0greenland0paraguay0zimbabwe0norway0japan0germany0finland0vietnam0malaysia0cote d'ivoire0poland0oman0italy0philippines0burkina faso0new zealand0gabon0ecuador0guinea0united kingdom0uganda0ghana0romania0laos0guyana0belarus0kyrgyz0senegal0syria0cambodia0uruguay0suriname0tunisia0bangladesh0nepal0tajikistan0greece0nicaragua0north korea0malawi0eritrea0benin"
 0¡                  # Split this by "0"
s                    # Swap to take the list of 0s and 1s again
 Ï                   # Only leave the strings which are truthy at the same index
                     # (and output the result implicitly)

See this 05AB1E tip of mine (sections How to use the dictionary?, How to compress strings not part of the dictionary?, How to compress large integers?, and How to compress integer lists?) to understand how the compression parts work.

1. Python 3.5, 1651 1458 1398 bytes

Script takes two arguments.
Lists are compressed using LZMA BZ2 zlib, encoded to Ascii85 and stored as two comment lines after fileheader. Script reads itself, decode and uncompress these lines.
#!/usr/bin/python3
#GhO`I6%\,>%(lBO\a@"&E!__Y)$A-Ff<:j\Zp8G1Q=R\[aL$##cd[#Pij[XO8YuBARE6=2nKRD/).0>%g#JDN88bcljG2%`4dgK<6&DcfL6B^8a,Q'!/kQ'%Y-V9;b`T;[FBm3&5T5Ys2U;CmXCF5:aq71_o,S+(:/uX&2L\fa_-/Kd'3s6'[G]sCn=J+=>6L_s/WA*`k@\':,lZ\ajllj%bUG0!qCp9F]27HBY(^&g;oVer&mCo)2`N/hX]II^\`uAc4tBW-9;`g,5d;uq]U>#PY..CpNFN`coGkC/^iJ/obu7<Xd,P9mG+g'N^u=3rEV<?>g(ktsJ*-0h`)JN0Qd/g$HOCkHOS9NOk5I@9mZQ(AT,&:D;D=6G:^[[=SHh;43Hhl.<kEAOiIW\\PrK;#`D?:k8qUU%%3@#\g19gTi`i0D3F,XH+;50n"r1ef9*)"a%bqYamDW(>P'r!bI:.gVAFJm8ke"\jNT^XS'D6lJVC=QibmBbdYu]A8q<$V4oh+DO0HR653:K@ZfLgC/3eQ1hYB;?.Jjffo6Hki<jQp>/o`2CO`l:75X50!JL1D.3e=%;ln5E%^0_p`^=LEEs0IQl*(,e5p
#GhOI,<t5?f#XeVP%DCQs@Uj%oUjWTD(l41.HE#\:p4+)_#$1Vhad1Jm5*P-3'#*CKij5)RT]`;4pYs(Neg<]+lVk(SN$V1O9Pimd<c%%.IW.a[YSm[1ht!C1:I<SVjZTUuYN)7^7#D((KD4T-=AM;V^T&UWbMi,>Ya\!/(t[6!A*tabY2Lt='tB`J]`oHWl03e4Qa=fZMu[=U-hfuQCD>b8o=4o2"T](^/'MZsb3+#T@&p,HQpC)FCec9Pc,M&NdXUa=S#I(4#dd3;6_)*Z5X]!WZ\%VJ@B<m-&^)`PH9K1r2i(<4Qn2P8MFP!EJj1eD\H@e>m"$h-X4`AC]fg"I/tPODfK,?*5Ru-l`$`>#lJhuVj.;nHE<`u/&mBdGT\n$Vp'4N#:<19D9Z+4@P<2aQG[ohN)/bpcZ+ghPo`GO.K*_
from base64 import*;from zlib import decompress;from sys import*;(f,t)=[*map(int,argv[1:3])];g=open(argv[0],"r");l=g.readlines();g.close()
def d(l,n):return decompress(a85decode(l[n][1:-1])).decode().split("\n")
n=d(l,1);a=d(l,2);o=[]
for i,b in enumerate(a):
    if f<=int(b)<=t:o.append(n[i])
print("{},{}\t->\t{}".format(f,t,", ".join(o)))

I know, it's not pretty to abuse comments like this. But it works... for golfing.
To include binary data in text file you need to encode it to printable chars only. But base64 encoding is not dense enough, that is why I used A85. But it has chars that need to be escaped in order to put this in python string.. So then I use comments :)
Explanation
# imports
from base64 import*
from zlib import decompress
from sys import*

# parse input as integers
(f,t)=[*map(int,argv[1:3])]

# open this file and read all lines
g=open(argv[0],"r");l=g.readlines();g.close()

# from array of lines get line n; strip leading "#" and trailing "\n"; decode from Ascii85; decompress; decode from bytes to string; split on newline
def d(l,n):return decompress(a85decode(l[n][1:-1])).decode().split("\n")

# decode list of names, list of areas and create empty output list
n=d(l,1);a=d(l,2);o=[]

# cycle through list of areas
for i,b in enumerate(a):

    # if curent area is between limits, append country to output list
    if f<=int(b)<=t:o.append(n[i])

# print formatted output
print("{},{}\t->\t{}".format(f,t,", ".join(o)))

edit: changed compression method and removed map(int) before enumerate
https://docs.python.org/3/library/zlib.html

Jelly, 736 bytes
“þṾṚSẸL£ỵƘhŀẠṗµA+QØḣœḢpṗżÐEn⁷ȦyẈ⁷g%v3ọṇ(Ƥd>OṾTṭAJẓṛṢƊƭḟ¢ẊȦ9c°ÐṄ5IqżQo⁾Ṣæṗʂ"OƥkpṙY!e}Q/ẆⱮṠyṄ0ØȥLYỊṃ~+æ+İbɠṇxƊƁjjtẓ?ạ5ỌżṆiⱮẆj/ȯ¬ẉ⁹Œ¿żÐX¥hẇyqJ~⁶Żḟ#1QJṗ¹n³H.ḋ(Ṣ^ỊẆKḲŒU[⁵6¢2ȯdG/⁼ṭḥİ!ƈ3ḤḳUıHṇlṄ⁽€ẆṠwẈƁḣḳµ!⁾³Ḋ¦Ṭḳ0ƈØʠ⁴æ?+Ịṙ4⁸8Żḅ| GḅɗṆĠKİb"ḃɲʠµY⁴ḟnỊẋ⁺V³ṚĖıknṠƊMeẓƬḌ⁺£©9⁴ȥøẓɦ&7ɱ_2ɠȷṂẋṚcṇṫḢ)MȮ¶I7ıṃ1LŻỌƊḞYrỴȦṠṣ3ḥ<Ƥ½’ḃ“¡æ⁽ż’e€³rƝḢ¤Tị“Ṇ¹zẏƥKDTịAjṇẒ¤<Ṁ6:-jOʂƑṆɠw@Ẉṙ]Ż§!œ~Cıu",©ḳṂƒḥ¢Ė~,ḲsĿỊƭṀjⱮḳ%o!Ðrḍ3©ƊZØq-JṪƤƘÑẹ04ⱮṂṛ'÷ƥÆƁ¦z¢Ẓ3kaṁ⁾ẏHnĊ^ḍỤfçÄŒṅṣḍƒb ybḤċÄæ¬).sḋ ėmẸeHẈŀ⁺U®`nɓƙt ZeNH+¥ḋỌLYÑ¥ḳƬȤƘ³ẓ½⁸¢ṛŻḍ\ƙß³ÞdȦḲµṫk¡ẓ⁶ẒṠƑ~ġ+=3þḌ÷z⁾ñ9cø.'3ṆN⁸0HḟN+ƒN⁼ƁKạṪƲ⁽żė@ÑṣT³ṠQƁ1ṭ©>]Ɱr&Ị}°rð0ċ4ntėṭiḣƤ^/æmẠ8ZṪ®$ÄOẏ¬⁻v!ƭh]ḟÄF^Ẇß2Ɗ8þṄÆ⁴)ƒṛ⁺ƭ©ẹẓÑ3⁵|F}ß8"ÞḂṣ⁷%ƙ9Ɱ:D¥ĖĠÆ7ƒṭṘ³ɓċ³ɱTƊDɼ>Ɗ;ẹẇÐƒµcKṁ⁺ḳRỤ®+®lUṛ½ẒʂƊḃNʋḥæṠḤmḲ³ɓÑ`Ɲṗ[]ṠȮẏ3lḍƤʂXṃ4#ʠ°µḄƈẈıḥıẉ®×ḊẈƝỤġOlṠÆU½ẏ½ċƒµKRW»Ỵ¤K

Try it online!

R, 1656 bytes
function(a,b)d$s[d$c>=a&d$c<=b];d=data.frame(strsplit("russia,canada,united states,china,brazil,australia,india,argentina,kazakhstan,congo,algeria,saudi arabia,mexico,indonesia,sudan,libya,iran,mongolia,peru,chad,niger,angola,mali,south africa,colombia,ethiopia,bolivia,mauritania,egypt,tanzania,nigeria,venezuela,namibia,mozambique,pakistan,turkey,chile,zambia,myanmar,afghanistan,south sudan,somalia,central african republic,ukraine,madagascar,botswana,kenya,france,yemen,thailand,spain,turkmenistan,cameroon,papua new guinea,sweden,uzbekistan,morocco,iraq,greenland,paraguay,zimbabwe,norway,japan,germany,finland,vietnam,malaysia,cote d'ivoire,poland,oman,italy,philippines,burkina faso,new zealand,gabon,ecuador,guinea,united kingdom,uganda,ghana,romania,laos,guyana,belarus,kyrgyz,senegal,syria,cambodia,uruguay,suriname,tunisia,bangladesh,nepal,tajikistan,greece,nicaragua,north korea,malawi,eritrea,benin",',')[[1]],c(17098250,9984670,9831510,9562911,8515770,7741220,3287259,2780400,2724902,2686860,2381740,2149690,1964380,1910931,1879358,1759540,1745150,1564120,1285220,1284000,1267000,1246700,1240190,1219090,1141749,1104300,1098580,1030700,1001450,947300,923770,912050,824290,799380,796100,785350,756096,752610,676590,652860,644330,637660,622980,603550,587295,581730,580370,549087,527970,513120,505940,488100,475440,462840,447420,447400,446550,435050,410450,406752,390760,385178,377962,357380,338420,330967,330800,322460,312680,309500,301340,300000,274220,267710,267670,256370,245860,243610,241550,238540,238390,236800,214970,207600,199949,196710,185180,181040,176220,163820,163610,147630,147180,141376,131960,130370,120540,118480,117600,114760))

Try it online!


text:
Minimum-cost flow problem
A flow network is a directed graph G = (V, E) with a source vertex s ϵ V and a sink vertex t ϵ V, and where every edge (u, v) ϵ E on the graph (connecting nodes u ϵ V and v ϵ V) has 2 quantities associated with it:

c(u, v) >= 0, the capacity of the edge
a(u, v) >= 0, the cost of sending one unit through the edge

We define a function 0 <= f(u, v) <= c(u, v) to be the number of units being passed through a given edge (u, v). Thus, the cost for a given edge (u, v) is a(u, v) * f(u, v). The minimum-cost flow problem is defined as minimizing the total cost over all edges for a given flow amount d, given by the following quantity:

The following constraints apply to the problem:

Capacity requirements: the flow through a given edge may not exceed the capacity of that edge (f(u, v) <= c(u, v)).
Skew symmetry: the flow though a given edge must be antisymmetric when the direction is reversed (f(u, v) = -f(v, u)).
Flow conservation: the net flow into any non-sink non-source node must be 0 (for each u ∉ {s, t}, summing over all w, sum f(u, w) = 0).
Required flow: the net flow out of the source and the net flow into the sink must both equal the required flow through the network (summing over all u, sum f(s, u) = sum f(u, t) = d).

Given a flow network G and a required flow d, output the minimum cost for sending d units through the network. You may assume that a solution exists. d and all capacities and costs will be non-negative integers. For a network with N vertices labeled with [0, N-1], the source vertex will be 0 and the sink vertex will be N-1.
This is code-golf, so the shortest answer (in bytes) wins. Remember that this is a competition within languages as well as between languages, so don't be afraid to post a solution in a verbose language.
Built-ins are allowed, but you are encouraged to include solutions without builtins, either as an additional solution in the same answer, or as an independent answer.
Input may be in any reasonable manner that includes the capacities and costs of each edge and the demand.
Test Cases
Test cases are provided in the following format:
c=<2D matrix of capacities> a=<2D matrix of costs> d=<demand> -> <solution>
c=[[0, 3, 2, 3, 2], [3, 0, 5, 3, 3], [2, 5, 0, 4, 5], [3, 3, 4, 0, 4], [2, 3, 5, 4, 0]] a=[[0, 1, 1, 2, 1], [1, 0, 1, 2, 3], [1, 1, 0, 2, 2], [2, 2, 2, 0, 3], [1, 3, 2, 3, 0]] d=7 -> 20
c=[[0, 1, 1, 5, 4], [1, 0, 2, 4, 2], [1, 2, 0, 1, 1], [5, 4, 1, 0, 3], [4, 2, 1, 3, 0]] a=[[0, 1, 1, 2, 2], [1, 0, 2, 4, 1], [1, 2, 0, 1, 1], [2, 4, 1, 0, 3], [2, 1, 1, 3, 0]] d=7 -> 17
c=[[0, 1, 4, 5, 4, 2, 3], [1, 0, 5, 4, 3, 3, 5], [4, 5, 0, 1, 5, 5, 5], [5, 4, 1, 0, 3, 2, 5], [4, 3, 5, 3, 0, 4, 4], [2, 3, 5, 2, 4, 0, 2], [3, 5, 5, 5, 4, 2, 0]] a=[[0, 1, 4, 2, 4, 1, 1], [1, 0, 3, 2, 2, 1, 1], [4, 3, 0, 1, 4, 5, 2], [2, 2, 1, 0, 2, 2, 3], [4, 2, 4, 2, 0, 4, 1], [1, 1, 5, 2, 4, 0, 2], [1, 1, 2, 3, 1, 2, 0]] d=10 -> 31
c=[[0, 16, 14, 10, 14, 11, 10, 4, 3, 16], [16, 0, 18, 19, 1, 6, 10, 19, 5, 4], [14, 18, 0, 2, 15, 9, 3, 14, 20, 13], [10, 19, 2, 0, 2, 10, 12, 17, 19, 22], [14, 1, 15, 2, 0, 11, 23, 25, 10, 19], [11, 6, 9, 10, 11, 0, 14, 16, 25, 4], [10, 10, 3, 12, 23, 14, 0, 11, 7, 8], [4, 19, 14, 17, 25, 16, 11, 0, 14, 5], [3, 5, 20, 19, 10, 25, 7, 14, 0, 22], [16, 4, 13, 22, 19, 4, 8, 5, 22, 0]] a=[[0, 12, 4, 2, 9, 1, 1, 3, 1, 6], [12, 0, 12, 16, 1, 2, 9, 13, 2, 3], [4, 12, 0, 2, 2, 2, 2, 10, 1, 1], [2, 16, 2, 0, 2, 1, 8, 4, 4, 2], [9, 1, 2, 2, 0, 5, 6, 23, 5, 8], [1, 2, 2, 1, 5, 0, 13, 12, 12, 1], [1, 9, 2, 8, 6, 13, 0, 9, 4, 4], [3, 13, 10, 4, 23, 12, 9, 0, 13, 1], [1, 2, 1, 4, 5, 12, 4, 13, 0, 13], [6, 3, 1, 2, 8, 1, 4, 1, 13, 0]] d=50 -> 213

These test cases were computed with the NetworkX Python library.

Sandbox

Golfing for a long time then realized I was golfing the wrong algorithm because I can't read

[R + lpSolve], 201 186 149 144 bytes
function(c,a,d,`^`=rep,N=ncol(c),G=diag(N),P=t(1^N),M=P%x%G+G%x%-P)lpSolve::lp(,a,rbind(M,diag(N*N)),c('=','<')^c(N,N*N),c(d,0^(N-2),-d,c))$objv

Try it online!
The code constructs the following Linear Problem and solve it using lpSolve package :
$$
\begin{align}
      min & \sum_{\forall x \in V}\  \sum_{\forall y \in V} A_{x,y} \cdot f_{x,y} \\
subject\ to : & \\
          & \sum_{x \in V} f_{v,x} - f_{x,v} = 0 & \forall v \in V : v \neq \{s,t\} \\
          & \sum_{x \in V} f_{s,x} - f_{x,s} = d \\
          & \sum_{x \in V} f_{t,x} - f_{x,t} = -d \\
          & f_{x,b} \leq C_{x,b}                 & \forall x \in V,\forall y \in V
\end{align}
$$
where :

\$V\$ is the set of vertices
\$s\$ s is the source vertex
\$t\$ s is the target (or sink) vertex
\$A_{x,y}\$ is the flow cost for edge x -> y
\$f_{x,y}\$ is the flow of edge x -> y in the optimal solution
\$d\$ is the required flow at sink (i.e. the demand at \$t\$ and the production at \$s\$)
\$C_{x,y}\$ is the maximum capacity of edge x -> y

Nice, linear programming :) Unfortunately most languages don't have an lpSolve... :(

That's unfortunately true... BTW it's not available on base-R, it's a package... I had to ask to install on TIO ;)

For some reason I have yet to find a short way of modifying MinCostMaxFlow to become MinCostFlow... my brain is fried lol, I wish there was a function for this in languages other than mathematica

@Quintec: are you referring to a specific implementation (e.g. in a certain language) of MinCostMaxFlow  ?

No, my hand coded algorithm

@Quintec: I see... not sure if that is actually possible since they have different goals and optimization "directions" (i.e. maximization of the flows vs minimization of the costs)

My thought is to reduce the maximum flow in the graph slowly until it becomes the desired flow... obviously it hasn't worked yet lol

@Quintec: eheh... optimization problems are hard to address :)

Wolfram Language, 42 bytes
FindMinimumCostFlow[#,1,VertexCount@#,#2]&

Trivial builtin. Non-builtin solution coming soon.

Is it coming in 6-8 weeks? :P

Python 3 + NetworkX, 137 bytes
from networkx import*
def f(g,d,z='demand'):N=len(g)**.5//1;G=DiGraph(g);G.node[0][z]=-d;G.node[N-1][z]=d;return min_cost_flow_cost(G)

No TryItOnline link because TIO doesn't have the NetworkX library installed
Takes graph input as an edge list with capacity and weight attributes, like this:
[(0, 0, {'capacity': 0, 'weight': 0}), (0, 1, {'capacity': 3, 'weight': 1}), (0, 2, {'capacity': 2, 'weight': 1}), (0, 3, {'capacity': 3, 'weight': 2}), (0, 4, {'capacity': 2, 'weight': 1}), (1, 0, {'capacity': 3, 'weight': 1}), (1, 1, {'capacity': 0, 'weight': 0}), (1, 2, {'capacity': 5, 'weight': 1}), (1, 3, {'capacity': 3, 'weight': 2}), (1, 4, {'capacity': 3, 'weight': 3}), (2, 0, {'capacity': 2, 'weight': 1}), (2, 1, {'capacity': 5, 'weight': 1}), (2, 2, {'capacity': 0, 'weight': 0}), (2, 3, {'capacity': 4, 'weight': 2}), (2, 4, {'capacity': 5, 'weight': 2}), (3, 0, {'capacity': 3, 'weight': 2}), (3, 1, {'capacity': 3, 'weight': 2}), (3, 2, {'capacity': 4, 'weight': 2}), (3, 3, {'capacity': 0, 'weight': 0}), (3, 4, {'capacity': 4, 'weight': 3}), (4, 0, {'capacity': 2, 'weight': 1}), (4, 1, {'capacity': 3, 'weight': 3}), (4, 2, {'capacity': 5, 'weight': 2}), (4, 3, {'capacity': 4, 'weight': 3}), (4, 4, {'capacity': 0, 'weight': 0})]

This is a golfed version of the code that I used to verify the test cases.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Generate the k-ary necklaces of length n
The set of necklaces is the set of strings, where two strings are considered to be the same necklace if you can rotate one into the other. Your program will take nonnegative integers k and n, and generate a list of the k-ary (fixed) necklaces of length n.
Necklaces will be represented by any representative string. So the necklace corresponding to the strings {ABC, BCA, CAB} can represented as ABC, BCA, or CAB.
The program will output a list of strings, such that each necklace is represented by exactly one string in the list. So for instance, outputting ABC and BCA would not be valid, since the same necklace was represented twice.
Some other details:

Your program may choose which k characters to use for the alphabet. If you prefer, you can instead choose k distinct values of any type, and have your program output lists (or some other sequence type) of those k values. (This might in fact be necessary if k is greater than the number of characters avaible in your language.) For example, if k=3, you could use {A,B,C}, {&, H, (}, or even {10, 11, 12} as your alphabet. The only restriction is that elements of your alphabet may not contain whitespace.
You may output any representative for each necklace. So for the necklace {ABC, BCA, CAB}, you may output ABC, BCA, or CAB. There is no "preferred" representative.

This is code-golf, so the shortest program wins!

Also, here is a useful test to see if your program is working. Given k and n, the list your program outputs have the length listed here. Here is an OEIS sequence corresponding to k=2.
Also, here are some examples and counterexamples. Note that these are not test cases, because any input has both an infinite number of correct and incorrect outputs. I will give inputs in the form (k,n).
Examples:

(2,2): [AA, BB, AB]
(2,2): [AA, BA, BB]
(2,2): [[1,0], [0,0], [1,1]]
(3,2): [AA, BB, CC, AB, BC, AC]
(2,3): [AAA, BBB, AAB, ABB]
(3,3): [AAA, BBB, CCC, AAB, AAC, ABB, ABC, ACB, ACC, BBC, BCC]
(0,n): [] (for positive integers n)
(k,0): [[]] (for nonnegative integers k)
(k,n): Search "necklaces with k colors and n beads" on wolfram alpha (for positive integers k and n)

Counterexamples:

(2,2): [AA, BB, AB, BA]
(2,2): [AA, BB]
(3,3): [AAA, BBB, CCC, AAB, AAC, ABB, ABC, ACC, BBC, BCC]
(3,3): [AAA, BBB, CCC, AAB, BAA, AAC, ABB, ABC, ACB, ACC, BBC, BCC]
(k,n): Any list whose length is different from this (for positive integers n)
(3,3): [AAA, BBB, CCC, AAB, BAA, AAC, ABB, ABC, ACC, BBC, BCC]

You could have a program that verifies outputs. I think examples would also be helpful.

@lirtosiast Well, that would also depend on the output format. Different languages have different notations for lists. I suppose I could make one for python and let people adapt it to different languages. Think that would help?

Related

Very closely related

@PeterTaylor Indeed. One "gotcha" to look out for though is that the number of necklaces is not the same as the number of lyndon words, because a lyndon word also needs to be distinct from all its rotations.

That's a slightly opaque way of phrasing it. Was that intentional?

@PeterTaylor What do you mean? Like I said, lyndon words are related but not exactly the same as necklaces.

The transparent way of phrasing it is that the necklaces of length n correspond to the Lyndon words of length d where d is a factor of n. I wondered whether you were deliberately avoiding that level of detail to not give people hints.

@PeterTaylor oh, I actually did not know that. That would be a pretty big hint by my standards, though.

Jelly, 8 bytes
ṗṙJṂȯƲ€Q

A dyadic Link accepting the alphabet size, k, on the left and the necklace length, n, on the right which yields a list of the necklaces using the positive integers up to k as the alphabet.
Try it online!
How?
ṗṙJṂȯƲ€Q - Link: integer k, integer n
ṗ        - Cartesian power of [1,2,...,k] with n
         -   i.e. all n-length lists using alphabet [1,2,...,k]
     Ʋ€  - last four links as a monad for €ach list, L:
  J      -   range of length - i.e. [1,2,...,n]
 ṙ       -   rotate left by each of those values - i.e. get all rotations
   Ṃ     -   minimum
    ȯ    -   logical OR with L (since the minimum of an empty list is 0 not [])
      Q  - unique values the resulting list

This appears to give the wrong answers if k or n are less than 2 (although I am not familiar enough with Jelly to know for sure).

Fixed it to agree with given examples for a cost of 1 byte, are there any remaining issues?

I do not see any. The problems seemed related to empty and singleton lists, but those issues are now fixed.

Python 2, 105 bytes
lambda k,n:{min(i[j:]+i[:j]for j in range(n or 1))for i in product(*[range(k)]*n)}
from itertools import*

Try it online!
Returns a set of tuples.

JavaScript (ES7),  123 116 115  113 bytes
Takes input as (k)(n). Each necklace is represented as an array of integers.
k=>g=(n,x=k**n,o=[])=>x--?g(n,x,o.some(a=>~(a+[,a]).search(b),b=[...Array(n)].map(_=>x/k**--n%k|0))?o:[b,...o]):o

Try it online!

Japt, 27 bytes
?UÆVoÃrï ®c £ZéYÃn gÃâ:[[]]

Try it online!
Outputs with numbers starting from 0 for the values. Inputs in reversed order (n then k). The r throws a fit for n = 0 so I had to add an significant special-case.
Explanation:
?                     :[[]]    #Special case: return [[]] if n is 0
 UÆ  Ã                         #Get n rows of:
   Vo                          # The numbers [0..k-1]
      rï                       #Get all possible lists containing one number from each row...
         ®          Ã          #For each of those lists:
          c                    # Fix the formatting
            £ZéYÃ              # Get every possible rotation
                 n g           # Choose the "minimum" one
                     â         #Remove duplicate lists

On input (3,4), it seems to be missing a necklace corresponding to [3,2,1].

@PyRulez Fixed, I think

Charcoal, 37 bytes
Ｎθ≔Ｘθ…⁰⊕Ｎη≔⊟ηζ¿ηＩＥΦζ⁼κ⌊﹪÷×ι⊕ζηζ﹪÷ιηθ¶

Try it online! Link is to verbose version of code. Explanation:
Ｎθ≔Ｘθ…⁰⊕Ｎη≔⊟ηζ

Input k and n and calculate the powers of k from 1 to n, but then keep kⁿ separately.
¿η...¶

If n is zero then just print a newline. (I could special-case 0 in the algorithm which would only cost two bytes but the resulting array only contains an empty array and Charcoal optimises that away on output, so you can't tell that the empty array is there.)
Φζ⁼κ⌊﹪÷×ι⊕ζηζ

For all the numbers from 0 to kⁿ, multiply them all by kⁿ+1, then divide by the above powers of k, then take the modulus of all of them by kⁿ. Keep only those numbers which equal the minimum of the resulting set.
ＩＥ...﹪÷ιηθ

Convert the numbers to reversed base k padded to length n for output using Charcoal's default output which is each element on its own line and each necklace double-spaced from the next necklace.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
A well linked challenge
An activity I sometimes do when I'm bored is to write a couple of characters in matching pairs.  I then draw lines (over the tops never below) to connect these characters.  For example I might write \$abcbac\$ and then I would draw the lines as:

Or I might write \$abbcac\$

Once I've drawn these lines I try to draw closed loops around chunks so that my loop doesn't intersect any of the lines I just drew.  For example, in the first one the only loop we can draw is around the entire thing, but in the second one we can draw a loop around just the \$b\$s (or everything else)

If we play around with this for a little while we will find that some strings can only be drawn so that closed loops contain all or none of the letters (like our first example).  We will call such strings well linked strings.
Note that some strings can be drawn in multiple ways.  For example \$bbbb\$ can be drawn in both of the following ways (and a third not included):
 or
If one of these ways can be drawn such that a closed loop can be made to contain some of the characters without intersecting any of the lines, then the string is not well linked. (so \$bbbb\$ is not well linked)
Task
Your task is to write a program to identify strings that are well linked.  Your input will consist of a string where every character appears an even number of times, and your output should be one of two distinct consistent values, one if the strings are well linked and the other otherwise.
In addition your program must be a well linked string meaning

Every character appears an even number of times in your program.
It should output the truthy value when passed itself.

Your program should be able to produce the correct output for any string consisting of characters from printable ASCII or your own program.  With each character appearing an even number of times.
Answers will be scored as their lengths in bytes with fewer bytes being a better score.
Hint

 A string is not well linked iff a contiguous non-empty strict substring exists such that each character appears an even number of times in that substring.

Test Cases
abcbac -> True
abbcac -> False
bbbb -> False
abacbc -> True
abcbabcb -> True
abcbca -> False

So to be clear: Whether a string has a total even number of every character is irrelevant to whether it's a well-linked string. That requirement applies only to programs' source code. This is of course only a matter of semantics, because programs are allowed to have undefined behavior for inputted strings having an odd total number of any character (and at least one submitted program takes advantage of this).

Regex (ECMAScript 2018 or .NET), 140 126 118 100 98 82 bytes
^(?!(^.*)(.+)(.*$)(?<!^\2|^\1(?=(|(<?(|(?!\8).)*(\8|\3$){1}){2})*$).*(.)+\3$)!?=*)
This is much slower than the 98 byte version, because the ^\1 is left of the lookahead and is thus evaluated after it. See below for a simple switcheroo that regains the speed. But due to this, the two TIOs below are limited to completing a smaller test case set than before, and the .NET one is too slow to check its own regex.
Try it online! (ECMAScript 2018)
Try it online! (.NET)
To drop 18 bytes (118 → 100), I shamelessly stole a really nice optimization from Neil's regex that avoids the need to put a lookahead inside the negative lookbehind (yielding an 80 byte unrestricted regex). Thank you, Neil!
That became obsolete when it dropped an incredible 16 more bytes (98 → 82) thanks to jaytea's ideas which led to a 69 byte unrestricted regex! It's much slower, but that's golf!
Note that the (|( no-ops for making the regex well-linked have the result of making the it evaluate very slowly under .NET. They do not have this effect in ECMAScript because zero-width optional matches are treated as non-matches.
ECMAScript prohibits quantifiers on assertions, so this makes golfing the restricted-source requirements harder. However, at this point it's so well-golfed that I don't think lifting that particular restriction would open up any further golfing possibilities.
Without the extra characters needed to make it pass the restrictions (101 69 bytes):
^(?!(.*)(.+)(.*$)(?<!^\2|^\1(?=((((?!\8).)*(\8|\3$)){2})*$).*(.)+\3))
It's slow, but this simple edit (for just 2 extra bytes) regains all the lost speed and more:
^(?!(.*)(.+)(.*$)(?<!^\2|(?=\1((((?!\8).)*(\8|\3$)){2})*$)^\1.*(.)+\3))
^
(?!
    (.*)               # cycle through all starting points of substrings;
                       # \1 = part to exclude from the start
    (.+)               # cycle through all ending points of non-empty substrings;
                       # \2 = the substring
    (.*$)              # \3 = part to exclude from the end
    (?<!               # Assert that every character in the substring appears a total
                       # even number of times.
        ^\2            # Assert that our substring is not the whole string. We don't
                       # need a $ anchor because we were already at the end before
                       # entering this lookbehind.
    |                  # Note that the following steps are evaluated right to left,
                       # so please read them from bottom to top.
        ^\1            # Do not look further left than the start of our substring.
        (?=
            # Assert that the number of times the character \8 appears in our
            # substring is odd.
            (
                (
                    ((?!\8).)*
                    (\8|\3$) # This is the best part. Until the very last iteration
                             # of the loop outside the {2} loop, this alternation
                             # can only match \8, and once it reaches the end of the
                             # substring, it can match \3$ only once. This guarantees
                             # that it will match \8 an odd number of times, in matched
                             # pairs until finding one more at the end of the substring,
                             # which is paired with the \3$ instead of another \8.
                ){2}
            )*$
        )
        .*(.)+         # \8 = cycle through all characters in this substring
        # Assert (within this context) that at least one character appears an odd
        # number of times within our substring. (Outside this negative lookbehind,
        # that is equivalent to asserting that no character appears an odd number
        # of times in our substring.)
        \3             # Skip to our substring (do not look further right than its end)
    )
)

I wrote it using molecular lookahead (103 69 bytes) before converting it to variable-length lookbehind:
^(?!.*(?*(.+)(.*$))(?!^\1$|(?*(.)+.*\2$)((((?!\3).)*(\3|\2$)){2})*$))
^
(?!
    .*(?*(.+)(.*$))       # cycle through all non-empty substrings;
                          # \1 = the current substring;
                          # \2 = the part to exclude from the end
    (?!                   # Assert that no character in the substring appears a
                          # total even number of times.
        ^\1$              # Assert that our substring is not the whole string
                          # (i.e. it's a strict substring)
    |
        (?*(.)+.*\2$)    # \3 = Cycle through all characters that appear in this
                          # substring.
        # Assert (within this context) that this character appears an odd number
        # of times within our substring.
        (
            (
                ((?!\3).)*
                (\3|\2$)
            ){2}
        )*$
    )
)

And to aid in making my regex itself well-linked, I've been using a variation of the above regex:
(?*(.+)(.*$))(?!^\1$|(?*(.)+.*\2$)((((?!\3).)*(\3|\2$)){2})*$)\1
When used with regex -xml,rs -o, this identifies a strict substring of the input that contains an even number of every character (if one exists). Sure, I could have written a non-regex program to do this for me, but where would be the fun in that?

wtf it's still being golfed

@ASCII-only and still being golfed...

Jelly, 20 bytes
ĠẈḂẸẆṖÇ€Ạ
ĠẈḂẸ
ẆṖÇ€Ạ

Try it online!
The first line is ignored. It's only there to satisfy the condition that every character appear an even number of times.
The next line first Ġroups indices by their value. If we then take the length of each sublist in the resulting list (Ẉ), we get the number of times each character appears. To check whether any of these are non-even, we get the last Ḃit of each count and ask whether there Ẹxists a truthy (nonzero) value.
Therefore, this helper link returns whether a substring cannot be circled.
In the main link, we take all substrings of the input (Ẇ), Ṗop off the last one (so that we don't check whether the entire string can be circled), and run the helper link (Ç) on €ach substring. The result is then whether Ạll substrings cannot be circled.

So, yeah, this would be my solution too, but, unfortunately, it's boring... :(

J, 34 bytes
2:@':.,|~*'>1(#.,)*/@(1>2|#/.~)\.\

Try it online!
-8 bytes thanks to FrownyFrog
original
J, 42 bytes
(*#'.,012&|@~#')=1#.[:,([:*/0=2&|@#/.~)\.\

Try it online!
explanation
(*#'.,012&|@~#') = 1 #. [: , ([: */ 0 = 2&|@#/.~)\.\

(*#'.,012&|@~#')                                       NB. this evaluates to 1
                                                       NB. while supplying extra
                                                       NB. chars we need.  hence...
                 =                                     NB. does 1 equal...
                   1 #.                                NB. the sum of...
                        [: ,                           NB. the flatten of...
                             (                  )\.\   NB. the verb in parens applied
                                                       NB. to every suffix of every
                                                       NB. prefix, ie, all contiguous
                                                       NB. substrings
                             ([: */ 0 = 2&|@#/.~)      NB. def of verb in paren:
                                             /.~       NB. when we group by each
                                                       NB. distinct char...
                              [: */                    NB. is it the case that
                                                       NB. every group...
                                           @#          NB. has a length...
                                    0 = 2&|            NB. divisible by 2...

@Deadcode Since handling that amounts to doing the opposite test for the whole string as for every other substring, it seems a safe bet that most solutions would leave that out. Testing with abc, only the Perl entry doesn't "fail" on it. (It has other problems though.)

@ØrjanJohansen You misunderstood. I said strings with an odd total number of any character (which only disqualifies programs' source code, not well-linked strings) can be well-linked, and this program returns falsey for some of those well-linked strings. The question explicitly allows this undefined behavior, so the program is valid. Jonah, I think it's really interesting that your program does this and I admire that you figured out a method that works this way. I would love an explanation. This kind of programming is completely alien to me so I don't understand the comments and code.

1:@':.,02|~*'=1(#.,)*/@(0=2|#/.~)\.\

2:@':.,|~*'>1(#.,)*/@(1>2|#/.~)\.\ also seems valid

Python 3.8 (pre-release), 66 bytes
lambda l,b={id}:len({str(b:=b^{c})for(c)in l})<len(l)#,<^fmnost{}#

Try it online!
The Era of Assignment Expressions is upon us. With PEP 572 included in Python 3.8, golfing will never be the same. You can install the early developer preview 3.8.0a1 here.
Assignment expressions let you use := to assign to a variable inline while evaluating to that value. For example, (a:=2, a+1) gives (2, 3). This can of course be used to store variables for reuse, but here we go a step further and use it as an accumulator in a comprehension.
For example, this code computes the cumulative sums [1, 3, 6]
t=0
l=[1,2,3]
print([t:=t+x for x in l])

Note how with each pass through the list comprehension, the cumulative sum t is increased by x and the new value is stored in the list produced by the comprehension.
Similarly, b:=b^{c} updates the set of characters b to toggle whether it includes character c, and evaluates to the new value of b. So, the code [b:=b^{c}for c in l] iterates over characters c in l and accumulates the set of characters seen an odd number of times in each non-empty prefix.
This list is checked for duplicates by making it a set comprehension instead and seeing if its length is smaller than that of s, which means that some repeats were collapsed. If so, the repeat means that in the portion of s seen in between those times every character encountered an even number of numbers, making the string non-well-linked. Python doesn't allow sets of sets for being unhashable, so the inner sets are converted to strings instead.
The set b is initialized as an optional arguments, and successfully gets modified in the function scope. I was worried this would make the function non-reusable, but it seems to reset between runs.
For the source restriction, unpaired characters are stuffed in a comment at the end. Writing for(c)in l rather than for c in l cancels the extra parens for free. We put id into the initial set b, which is harmless since it can start as any set, but the empty set can't be written as {} because Python will make an empty dictionary. Since the letters i and d are among those needing pairing, we can put the function id there.
Note that the code outputs negated booleans, so it will correctly give False on itself.

Try it online!

Python 2, 74 bytes
bmn0=f=lambda s,P={0},d=[]:s<" "if(P in d)else+f(s[f<s:],P^{s[0^0]},[P]+d)

Try it online!
Iterates through the string, keeping track in P of the set of characters seen an odd number of times so far. The list d stores all past values of P, and if see the current P already in d, this means that in the characters seen since that time, each character has appeared an even number of times. If so, check if we've gone through the entire input: if we have, accept because the whole string is paired as expected, and otherwise reject.
Now about the source restriction. Characters needing pairing are stuffed into various harmless places, underlined below:
bmn0=f=lambda s,P={0},d=[]:s<" "if(P in d)else+f(s[f<s:],P^{s[0^0]},[P]+d)
_____              _              _      _    _    ___        ___

The f<s evaluates to 0 while pairing off an f, taking advantage of the function name also being f so that it's defined (by the time the function is called.) The 0^0 absorbs an ^ symbol.
The 0 in P={0} is unfortunate: in Python {} evaluates to an empty dict rather than an empty set as we want, and here we can put in any non-character element and it will be harmless. I don't see anything spare to put in though, and have put in a 0 and duplicated it in bmn0, costing 2 bytes. Note that initial arguments are evaluated when the function is defined, so variables we define ourselves can't be put in here.

Perl 6, 76 bytes
*.comb[^*X+(^*).map(^*)].grep({$_&[&]($_)}).none.Bag{*}.none%2#*^+XBob2rec%#

Try it online!
A Whatever lambda that returns a None Junction of None Junctions that can be boolified to a truthy/falsey value. I would recommend not removing the ? that boolifies the return result though, otherwise the output gets rather large.
This solution is a little more complex than needed, due to several involved functions being unlinked, e.g. .., all, >>, %% etc. Without the source restriction, this could be 43 bytes:
*.comb[^*X.. ^*].grep(?*).one.Bag{*}.all%%2

Try it online!
Explanation:
*.comb                     # Split the string to a list of characters
      [^*X+(^*).map(^*)]   # Get all substrings, alongside some garbage
                        .grep({$_&[&]($_)})        # Filter out the garbage (empty lists, lists with Nil values)
                                           .none                 # Are none of
                                                .Bag{*}          # The count of characters in each substring
                                                       .none%2   # All not divisible by 2

                                               #*^+XBob2rec%#    And garbage to even out character counts

Retina, 150 96 bytes
^(?!(.*)(.+)(.*)$(?<!^\2|^\1(?:(^?(?:(?!\6).)*\6){2})*(|(?!\6).)*(?!.+\6.*\3$)(.){1,}\3)(?!,<)?)

Try it online! Link includes test cases, including itself. Edit: Golfed down the original regex a fair bit with help from @Deadcode, then padded back up slightly less extravagently to maintain the source layout. Explanation:
^(?!(.*)(.+)(.*)$

Assert that no substring \3 exists that matches the following constraints.
(?<!^\2|

Assert that the substring is not the whole original string.
^\1(?:(^?(?:(?!\6).)*\6){2})*(|(?!\6).)*(?!.+\6.*\3$)(.){1,}\3)(?!,<)?)

Assert that there is no character \6 such that:

it does not appear between the character itself (exclusive) and the end of the substring
it appears an even number of times between the start of the substring and itself (exclusive)

In order to pass the source layout constraint, I replaced (((( with (?:(^?(?:( and (( with (|(. I still had one source constraint )) left and the characters !()1<{} left over, so I changed a + into {1,} and inserted the useless (?!,<)? to consume the rest.

This seems not to satisfy the restricted source requirements.

@ØrjanJohansen Finally, I've come up with a valid solution. Lots of junk in there though, so there might be something shorter available...

Perl 5 -p, 94, 86, 78 bytes
m-.+(?{$Q|=@q&grp,$\|=$&eq$_^!grep+/^/&(@m=$g=~/\Q$_/g),($g=$&)=~/./g})(?!)-}{

ouput 0 if well-linked 1 otherwise.
78 bytes
86 bytes
94 bytes
How it works

-p with }{ ending trick to output $\ at the end
m-.+(?{ .. })(?!)-, to execute code over all non-empty substring (.+ matches the whole string first, and after executing code between (?{ ..}) backtracks because of failed forced (?!)
$Q|=@q&grp, garbage because of source restriction
$\|= integer bitwise or assignment, if there's almost one 1, $\ will be 1 (true), by default it is empty (false)
$&eq$_ the case where the sbustring is the whole string is bitwise xored ^ with "no odd character occurence"
($g=$&)=~/./g to copy the matched substring into $g (because will be overwirtten after next regex match) and return the array of character of substring.
/^/ garbage which evaluates to 1
grep 1 &(@m=$g=~/\Q$_/g), for each character in substring get the array of character in $g matching itself, array in scalar evaluates to its size and grep to filter the chracters with odd occurence 1&x is equivalent to x%2==1

I don't think this satisfies the source restriction: I count an odd number of open parentheses, for example

@msh210 Isn't that the point? If there's an even number, it's not well linked

@Quintec One of the requirements for being well linked is that there are an even number of each character.

my first answer had the requirement but after trying to golf, lost it. updated, but can be golfed.

@ØrjanJohansen Having an even number of each character is not a requirement for a string being well-linked, it's just a requirement for the programs' source code.

@Deadcode "In addition your program must be a well linked string meaning - Every character appears an even number of times in your program."

@ASCII-only Then the challenge's description contradicts itself. The Hint says "iff" meaning "if and only if" – that means it contains a complete definition of what makes a string well-linked – and it does not mention odd or even total numbers of characters.

all the sources here satisfy source restriction, also the code returns 0 if well-linked and even number of each character

C# (Visual C# Interactive Compiler), 208 206 200 198 bytes
x=>!x.GroupBy(c=>c).Any(g=>g.Count()%2>0)&!Enumerable.Repeat(x.Count,x.Count*x.Count).Where(
(l,i)=>i%l>0&!x.Skip(i/l).Take(i%l).GroupBy(c=>c).Any(g=>g.Count()%2>0)
).Any()/*>!oyAnC0EmeablR*WhiS/T*/

Try it online!
-2 bytes thanks to @KevinCruijssen!
Finally got it below 200, so I might be done golfing for now :) I ended up creating a second TIO to test things out based on a previous answer.
Try it online!
Things that made this task tricky:

Equality operator == was not allowed
Increment/assign operator ++ was not allowed
Linq All() function was not allowed

Commented code below:
// anonymous function that takes an IList as input
x=>
  // the first condition makes sure the string even
  // counts of each character
  !x.GroupBy(c=>c).Any(g=>g.Count()%2>0)&
  // the second condition generates all proper substrings of x
  // and tests for any that contain even character counts
  // the string length `l` is repeated `l*l` times
  !Enumerable.Repeat(x.Count,x.Count*x.Count)
    .Where((l,i)=>
      // check that the substring length is greater than 0
      i%l>0&
      // use skip/take to generate a substring
      // and check for a character count thats odd
      // negate the result meaning we have found
      // a substring that invalidates the input
      !x.Skip(i/l).Take(i%l)
        .GroupBy(c=>c).Any(g=>g.Count()%2>0)
    )
    // if any invalid substrings are found
    // then the result in invalid
    // the comment string at the end is needed
    // to make the program well-linked
    .Any()/*>!oyAnC0EmeablR*WhiS/T*/

You can remove the two spaces in your trailing comment.

@KevinCruijssen - good one :) I had forgotten that I added a space already. I had to throw another one into the source.

Brachylog, 16 bytes
sᶠb∋p~j&sᶠb∋p~j&

Try it online!
Prints false. for truthy instances and true. for falsy instances.
The TIO version is too slow to handle itself, but it's clearly well-linked since it's a string with unique characters repeated twice.
Explanation
    Input is a string: "abcacbaa"
sᶠ  Find all substrings: ["abcacbaa","abcacba","abcacb",..,"a"]
b   Behead (now the proper substrings remain): ["abcacba","abcacb",..,"a"]
∋   Take one of them: "abcacb"
p   Permute it: "abcabc"
~j  It is some string repeated twice: "abc"
&   Get the input again: "abcacbaa"
    Then repeat the above.
    If the constraints can be satisfied, the result is true, otherwise false.

Python 2, 108 bytes
lambda d,e=enumerate:min(max(d[l:l+b].count(k)%2for(k)in d)for b,c in e(d[2:],2)for l,f in e(d) )#b =:x+.%2#

Try it online!
-2 thanks to Ørjan Johansen.

@ØrjanJohansen Huh, nice. EDIT: Looks like it saves only two bytes overall.

05AB1E, 22 20 bytes
Œε¢Pà}KŒIKεSIS¢ÈP}àÈ

Outputs 1 if the string is well-linked, and 0 if the string is not well-linked.
Try it online or verify all test cases.
Explanation:
The base program is ŒsKεsS¢ÈP}à (11 bytes), which outputs 0 if well-linked and 1 if not well-linked. The trailing È (is_even) is a semi no-op that inverts the output, so 1 for well-linked strings and 0 for not well-linked strings. The other parts are no-ops to comply to the challenge rules.
Œε¢Pà}K         # No-ops: substrings, map, count, product, maximum, close map, remove
                # Due to the last remove, we're back at the (implicit) input again
Œ               # Take the substrings of the input
 IK             # Remove the input itself from that list of substrings
   ε            # Map each substring to:
    S           #  No-op: transform the substring into a list of characters
     IS         #  Get the input-string as a list of characters
       ¢        #  Count the occurrence of each character in the current substring
        È       #  Check which counts are even (1 if truthy; 0 if falsey)
         P      #  Take the product of that
          }à    # After the map: check if any are truthy by taking the maximum
            È   # Semi no-op: check if this maximum is even (0 becomes 1; 1 becomes 0)
                # (and output the result implicitly)


text:
A Turtle Finds a Portal
The turtle wants to move along the grid to get to his food. He wants to know how many moves it will take for him to get there.
As well since he is slow he has teleporters set up around his domain that he will utilize if it shortens his path. Or avoid them if it lengthens his path.
Meet the turtle

The turtle lives on a grid
$$\begin{matrix}
X&X&X&X&X\\
X&X&X&X&X\\
X&X&&X&X\\
X&X&X&X&X\\
X&X&X&X&X\\
\end{matrix}$$
The turtle can move to any adjacent square...
$$\begin{matrix}
X&X&X&X&X\\
X&\nwarrow&\uparrow&\nearrow&X\\
X&\leftarrow&&\rightarrow&X\\
X&\swarrow&\downarrow&\searrow&X\\
X&X&X&X&X\\
\end{matrix}$$
However, the turtle cannot move to a square with a mountain
$$\begin{matrix}
X&&X&X&X\\
X&\nwarrow&\uparrow&\nearrow&X\\
X&&&\rightarrow&X\\
X&&\downarrow&\searrow&X\\
X&&X&X&X\\
\end{matrix}$$
The Turtle wants to eat his Strawberry, and would like to know how long it will take to get to his Strawberry
$$\begin{matrix}
X&&\\
&&X\\
X&&X\\
X&X&X\\
\end{matrix}$$
This example would take the turtle \$5\$ turns
$$\begin{matrix}
X&&\\
\downarrow&&\uparrow\\
\searrow&&\uparrow\\
X&\nearrow&X\\
\end{matrix}$$
Luckily, the Turtle found a teleporter! There are two teleports on the grid that map to each other. Stepping on the teleporter immediately moves the turtle to the corresponding teleporter. Teleporters are very unstable and after using them once, they disapear and are no longer useable.
$$\begin{matrix}
&&\\
&&\\
X&&X\\
X&X&X\\
\end{matrix}$$
It is now faster for the turtle to move up twice. Now the turtles shortest path is \$2\$
$$\begin{matrix}
&&\\
\uparrow&&\uparrow\\
X&&X\\
X&X&X\\
\end{matrix}$$
The challenge
Given an initial grid configuration output the number of moves it will take the turtle to reach his strawberry.
Rules

You may assume that the input grid has a solution

Each grid will only have one strawberry and two portals and one turtle

The input grid may be entered in any convenient format

You should treat teleporters are single use items

The turn that the turtle moves onto a teleporter square he is already on the corresponding teleporter. He never moves onto a teleporter and stays there for a move

The shortest path does not need to make use of the portal

The turtle cannot pass into mountain tiles

You may use any ASCII character or integer to represent mountains, turtle, empty grid square, strawberry

You may use either the same character or two different ASCII characters or integers to represent the teleporter pairs

A grid can have more than one path with the same shortest path length

This is code-golf

Clarifications to Rules

You should treat teleporters are single use items.

Reasoning: It was pointed out that the case of:
$$\begin{matrix}
&X&&X&\\
&&&&&\\
&X&X&X&X
\end{matrix}$$
Could be only solved by entering and exiting the portals twice. At the time of making this clarification both solutions acted by assuming they were either single use, or there was no reason to try previously used squares. To avoid breaking their hard-worked solutions, this seemed the best way account for this set up. Therefore, this would be considered an invalid grid.
Test Cases formatted as lists
[ ['T', 'X', 'X', 'S', 'X'], ['X', 'X', 'X', 'X', 'X'], ['X', 'X', 'X', 'X', 'X'] ] --> 3
[ ['T', 'M', 'X', 'S', 'X'], ['X', 'M', 'X', 'X', 'X'], ['O', 'X', 'X', 'X', 'O'] ] --> 4
[ ['T', 'M', 'X', 'S', 'O'], ['O', 'M', 'X', 'X', 'X'], ['X', 'X', 'X', 'X', 'X'] ] --> 2
[ ['T', 'M', 'X', 'S', 'X'], ['O', 'M', 'X', 'X', 'X'], ['O', 'X', 'X', 'X', 'X'] ] --> 4
[ ['T', 'M', 'S', 'X', 'O'], ['X', 'M', 'M', 'M', 'M'], ['X', 'X', 'X', 'X', 'O'] ] --> 7
[ ['T', 'X', 'X', 'S', 'X'], ['O', 'M', 'M', 'M', 'X'], ['X', 'X', 'O', 'X', 'X'] ] --> 3

Test Cases formatted for humans
T X X S X
X X X X X
X X X X X --> 3

T M X S X
X M X X X
O X X X O --> 4

T M X S O
O M X X X
X X X X X --> 2

T M X S X
O M X X X
O X X X X --> 4

T M S X O
X M M M M
X X X X O --> 7

T X X S X
O M M M X
X X O X X --> 3

Credits
Design and structure via: Hungry mouse by Arnauld
Proposed Challenges Edit Advice: Kamil-drakari, beefster
General Edit Advice: okx nedla2004 mbomb007

I think it would be a good idea to add a test case where using the teleporter would make it take longer.

@Okx Creating and adding now.

What happens when an unwanted teleporter is in the way, like TXOXS,MMMMM,OXXXX? Does the turtle have to move off the other end of the teleporter and go back onto it? What if that's not possible like TXOXS,MMMMM,OMXXX?

Your first case would result in the turtle going through and then re-entering. The second case would be un solvable; not a valid grid.

@xnor I feel that this may be to abstract from my original rules. So perhaps it's better to portals a one use item?

@akozi I'm not sure, I think both options make for complications for some class of solutions.

@xnor Yes very true. I'm disappointed in myself for not thinking of this case before posting. I think at the moment both solutions posted act by assuming the portal is a one time use. Based on this I think it makes sense to set them as one time uses to avoid breaking their hard worked answer. This then would set the case of TXOXS,MMMMM,OXXXX to be impossible, which I think is fine.

Related (I think).

JavaScript (ES7),  140 139  138 bytes
Takes input as a matrix of integers with the following mapping:

\$-1\$ =  (any portal)
\$0\$ = \$X\$ (empty)
\$1\$ =  (mountain)
\$2\$ =  (turtle)
\$3\$ =  (strawberry)

m=>(R=g=(t,X,Y,i)=>m.map((r,y)=>r.map((v,x)=>r[(u=0,t?v-t:(x-X)**2+(y-Y)**2<3?v-3?~v?v:u--:R=R<i?R:i:1)||g(u,x,y,u-~i,r[x]=1),x]=v)))(2)|R

Try it online!
How?
The main recursive search function \$g\$ is able to either look for a specific tile \$t\$ on the board (if it's called with \$t\ne 0\$) or for any tile at \$(x,y)\$ which can be reached from the current position \$(X,Y)\$.
It keeps track of the length of the current path in \$i\$ and updates the best result \$R\$ to \$\min(R,i)\$ whenever the turtle finds the strawberry.
It is first called with \$t=2\$ to find the starting position of the turtle.
It calls itself with \$t=-1\$ if a portal is reached, so that the turtle is teleported to the other portal. We do not increment \$i\$ during such an iteration.
Each visited tile is temporarily set to a mountain to prevent the turtle from moving twice on the same tile in the same path. If we get trapped in a dead-end, the recursion simply stops without updating \$R\$.
Commented
m => (                        // m[] = input matrix
  R =                         // initialize R to a non-numeric value
  g = (t, X, Y, i) =>         // g = recursive search function taking t = expected tile,
                              //     (X, Y) = current coordinates, i = path length
    m.map((r, y) =>           // for each row r[] at position y in m[]:
      r.map((v, x) =>         //   for each tile v at position x in r[]:
        r[                    //     this statement will eventually restore r[x] to v
          ( u = 0,            //     u = next tile to look for, or 0 if none
            t ?               //     if we're looking for a specific tile:
              v - t           //       test whether we've found it
            :                 //     else:
              (x - X) ** 2 +  //       compute the squared Euclidean distance between
              (y - Y) ** 2    //       (x, y) and (X, Y)
              < 3 ?           //       if it's less than 3 (i.e. reachable from (X, Y)):
                v - 3 ?       //         if v is not equal to 3:
                  ~v ?        //           if v is not equal to -1:
                    v         //             test if v = 0
                  :           //           else (v = -1):
                    u--       //             set u = -1 to find the other portal
                :             //         else (v = 3):
                  R = R < i ? //           we've found the strawberry: set R = min(R, i)
                      R : i   //
              :               //       else (this tile can't be reached):
                1             //         yield 1
          ) ||                //     if the above result is falsy:
          g(                  //       do a recursive call:
            u,                //         t = u
            x, y,             //         move to (x, y)
            u - ~i,           //         unless u is set to -1, increment i
            r[x] = 1          //         set this tile to a mountain
          ),                  //       end of recursive call
          x                   //     restore r[x] ...
        ] = v                 //     ... to v
    ))                        // end of both map() loops
)(2) | R                      // initial call to g with t = 2; return R

"Each visited tile is temporarily set to a mountain to prevent the turtle from moving twice on the same tile" What a lovely trick. Great answer, and as always I appreciate answers with explanations :)

Python 2, 441 431 341 bytes
from itertools import*
G=input()
W=len(G[0])
H=len(G)
A=[0]*5
E=enumerate
for y,r in E(G):
 for x,C in E(r):A[C]=[x,y]
for L in count():
 for M in product(*[zip('UDLR'*2,'LRDU    ')]*L):
  x,y=A[0]
  for m in M:
    x+='R'in m;x-='L'in m;y+='D'in m;y-='U'in m
    if(x,y)==A[3]:x,y=A[2]
    if 1-(W>x>-1<y<H)or G[y][x]>3:break
  if[x,y]==A[1]:exit(L)

Try it online!
Input as lists, but using numbers instead of characters (thanks to Quintec) and a seperate value for the destination of the teleporter. Those large indentations should be tab characters if Stack Exchange removes them. Any tips or ideas especially welcome, as I feel that this could get much somewhat shorter.
The table for characters used in the challenge to the numbers used for my program is below, but you can also use this program.
Challenge | My program
T         | 0
S         | 1
E         | 2
O         | 3
M         | 4
X         | -1

-10 bytes thanks to Quintec by changing the input from using characters to numbers.
-A lot of bytes thanks to Jonathan Frech, ElPedro, and Jonathan Allan.

You can probably shave a few characters off by taking in a list where each object is represented by a number instead of a string character.

@Quintec Added, thanks. I would like to do the same for the directions, but then the diagonals would have to be done separately. It still may be possible to move them to numbers though.

@JonathanFrech Sorry, I had changed the TIO to use Quintec's idea, but I had not updated the post. With their idea, yours can no longer be used. I should have updated the code in the post earlier.

@nedla2004 No problem. You can now probably golf if'U'in m:y-=1 to y-='U'in m, continuing analogously for the other lines.

You can use exit(L) to print the result as a return code so losing a couple of breaks and the E variable for 409

405 actually

By combining the great tip from @JonathanFrech with mine (and a couple of other minor golfs)  you're down to 384

I got 370

@JonathanAllan Very nice as always. You were looking at a different part of the code than I was :)

I still think we should be able to do something with the 4 if statements at the top but no matter how hard I try, I can't work out a better way of doing it.

@ElPedro Ahha I can shave 4 off like this

...and another 10 for 356

@JonathanAllan and ElPedro and Jonathan French. Great tips from all of you, and I have added them together with I couple things I came up with. (After much delay)

Python 2, 391 397 403 422 bytes
M=input()
from networkx import*
a=b=c=d=0
N,h,w,S=[-1,0,1],len(M),len(M[0]),[]
for i in range(h):
 for j in range(w):
  I,m=(i,j),M[i][j]
  if m>7:c,d=a,b;a,b=I
  if m<0:Z=I
  if m==5:F=I
  S+=[I+I]
S+=[(a,b,c,d),(c,d,a,b)]
print len(shortest_path(from_edgelist([((A+p,B+q),(C,D))for A,B,C,D in S for p,q in[(p,q)for p in N for q in N]if-1<A+p<h and-1<B+q<w and M[C][D]*M[A+p][B+q]]),Z,F))-1

Try it online!
The problem is translated into a graph and the solution is to find the shortest path form the turtle to the strawberry.
Challenge | This code
T         | -1
S         |  5
O         |  8
M         |  0
X         |  1


text:
Covering a Skyline with brush strokes
Given a non-negative integer skyline height list, answer how many uninterrupted 1-unit-high horizontal brush strokes are needed to cover it.
[1,3,2,1,2,1,5,3,3,4,2], visualised as:
      5
      5  4
 3    5334
 32 2 53342
13212153342

needs nine brush strokes:
      1
      2  3
 4    5555
 66 7 88888
99999999999

Examples
[1,3,2,1,2,1,5,3,3,4,2] → 9
[5,8] → 8
[1,1,1,1] → 1
[] → 0
[0,0] → 0
[2] → 2
[2,0,2] → 4
[10,9,8,9] → 11

For interested high-rep users: Based on this as per this.

So, all brush strokes are horizontal?

@tsh Good point. Added.

It wasnt codegolf, but I had this question for an interview code test about a year ago.

JavaScript (Node.js), 38 bytes
a=>a.map(v=>(n+=v>p&&v-p,p=v),p=n=0)|n

Try it online!
Simply a greedy algorithm which scan from left to right, only draw lines if needed, and draw it as long as possible.
Thanks Arnauld, save 2 3 bytes

@Arnauld nice catch. totally forgot it.

How did you realise this?

@Adám Nothing magic. First time I read the question I was confused by how to search until i realize all lines are horizontal only. And then this formula just came up to my mind naturally....

magic seems like a well-fitting word to describe that process.

Wish I had seen this before reading the explanation in Arnauld's answer so I could at least try to figure out how it works.

While this is the origin of the now widely used algorithm, it is explained here.

05AB1E,  8 7  5 bytes
Saved 2 bytes thanks to @Adnan
0š¥þO

Try it online!
How?
This is using the algorithm that was first found by @tsh. If you like this answer, make sure to upvote their answer as well!
Each time a skyscraper is lower than or as high as the previous one, it can be painted 'for free' by simply extending the brushstrokes.
For instance, painting skyscrapers \$B\$ and \$C\$ in the figure below costs nothing.
On the other hand, we need 2 new brushstrokes to paint skyscraper \$E\$, no matter if they're going to be reused after that or not.

For the first skyscraper, we always need as many brushstrokes as there are floors in it.
Turning this into maths:
$$S=h_0+\sum_{i=1}^n \max(h_i-h_{i-1},0)$$
If we prepend \$0\$ to the list, this can be simplified to:
$$S=\sum_{i=1}^n \max(h_i-h_{i-1},0)$$
Commented
0š¥þO     # expects a list of non-negative integers  e.g. [10, 9, 8, 9]
0š        # prepend 0 to the list                    -->  [0, 10, 9, 8, 9]
  ¥       # compute deltas                           -->  [10, -1, -1, 1]
   þ      # keep only values made of decimal digits
          # (i.e. without a minus sign)              -->  ["10", "1"]
    O     # sum                                      -->  11

I think 0š¥ʒd}O saves you a byte.

@Don'tbeax-tripledot I was editing my answer to exactly that when I saw your comment ;)

Beautiful explanation.

Replacing ʒd} with þ should save you two bytes.

@Adnan Ah, nice. Thanks!

@Adnan Where did you get that? Can't find it here: https://github.com/Adriandmen/05AB1E/wiki/Commands

Why does Digits of a extract positive numbers from a list?

@Sarien I guess it's filtering values matching /^[0-9]+$/.

Haskell, 32 bytes
(0%)
p%(h:t)=max(h-p)0+h%t
p%_=0

Try it online!
An improvement on Lynn's solution that tracks the previous element p instead of looking at the next element. This makes the base case and recursive call shorter in exchange for needing to invoke (0%).
max(h-p)0 could be max h p-p for the same length.

Haskell, 35 bytes
f(a:b:c)=max(a-b)0+f(b:c)
f a=sum a

Try it online!
Line 2 could be f[a]=a if I didn't also have to handle the case [].

Here's some competition.

Python 3, 37 bytes
lambda a:sum(a)-sum(map(min,a[1:],a))

Try it online!
-5 bytes by switching to Python 3, thanks to Sarien

Python 2, 47 43 42 bytes
lambda a:sum(a)-sum(map(min,a[1:],a[:-1]))

Try it online!
Alt:
lambda a:sum(a)-sum(map(min,zip(a[1:],a)))

Try it online!

In Python 3 you can ditch the [:-1], saving 5 bytes.

@Sarien Thanks :D, I didn't know map is different in python 2 and 3

Jelly, 5 bytes
A port of my 05AB1E answer, which itself is similar to @tsh JS answer.
ŻI0»S

Try it online!
Commented
ŻI0»S    - main link, expecting a list of non-negative integers  e.g. [10, 9, 8, 9]
Ż        - prepend 0                                             -->  [0, 10, 9, 8, 9]
 I       - compute the deltas                                    -->  [10, -1, -1, 1]
  0»     - compute max(0, v) for each term v                     -->  [10, 0, 0, 1]
    S    - sum                                                   -->  11

Haskell, 34 32 bytes
2 bytes trimmed by Lynn
g x=sum$max 0<$>zipWith(-)x(0:x)

Try it online!
So to start we have zipWith(-).  This takes two lists and produces a new list of their pairwise differences.  We then combine it with x and (0:x).  (0:) is a function that adds zero to the front of a list and by combining it with zipWith(-) we get the differences between consecutive elements of that list with a zero at the front.  Then we turn all the negative ones to zero with (max 0<$>).  This creates a new list where each element is the number of new strokes that has to be started at each tower.  To get the total we just sum these with sum.

g x=sum$max 0<$>zipWith(-)x(0:x) is 32 bytes :)

As is sum.zipWith((max 0.).(-))<*>(0:)

@Lynn Your second one is going to need extra parentheses since the . has higher precedence than <*>.

K (oK), 12 7 bytes
-5 bytes thanks to ngn!
A  k (oK) port of Arnauld's 05AB1E solution (and tsh's JavaScript solution):
+/0|-':

Try it online!
J, 15 bytes
A J port of Arnauld's 05AB1E solution (and tsh's JavaScript solution):
1#.0>./2-~/\0,]

Try it online!
My naive solution:
J, 27 bytes
1#.2(1 0-:])\0,@|:@,~1$~"0]

Try it online!

oK: each prior (':) uses an implicit identity element (0 for -) before the list, so 0, is unnecessary. you can omit { x} to make it a composition: +/0|-':

@ngn Thanks! Apparently I've forgotten this: Some primitive verbs result in a different special-cased initial value: +, *, - and & are provided with 0, 1, 0 or the first element of the sequence, respectively

Dyalog APL, 11 bytes
+/0⌈¯2-/0,⊢

, concatenate, so 0, concatenates 0.
¯2-/
or
¯2 length of window. (minus means the window is rotated)
-/ does a window operation of -(minus) with window size 2
0⌈ the operation is called ceiling, but when it gets an input from both sides it also does "get the larger of the two inputs" so 0⌈1 3 0 ¯2 will give 1 3 0 0.
and finally, a +/ which is a sum.
Try it!

Here is a link which you could add to your post to help others test your solution. If you click on Postify over there it will also provide you with some formatting for the answer

I've fixed your formatting and byte count (assuming you use some for of Single Byte Character Set), and included ovs's link.

Thanks for the help!

Somehow this works for negative towers as well. Very neat.

correction,  this works for negative numbers: +/0⌈2-⍨/0,0,⍨⊢
it actually fails if you do 0 ¯3

Welcome to Code Golf, by the way!

Japt, 8 bytes
-2 bytes from @Shaggy
mîT Õ¸¸è

Explanation
mîT Õ¸¸è      Full program. Implicit input U
                e.g. U = [2,0,2]
mîT             Map each item X and repeat T(0) X times
                     U = ["00","","00"]
    Õ           Transpose rows with columns
                     U = ["0 0","0 0"]
     ¸¸         Join using space and then split in space
                     U = ["0","0","0","0"]
        è       Return the count of the truthy values

Try it online!

8 bytes: mîT Õ¸¸è

Nice use of A.y()'s padding, by the way.

MATL, 8 bytes
0whd3Y%s

Try it online!
Pretty much @Arnauld's algorithm. Saved one byte (thanks @LuisMendo) by casting to uint64 rather than selecting ) positive entries.

R, 30 bytes
sum(pmax(0,diff(c(0,scan()))))

Try it online!
Porting of @Arnauld solution which in turn derives from @tsh great solution

Japt -x, 7 6 bytes
änT f¬

Try it
1 byte saved thanks to Oliver.
änT f¬     :Implicit input of integer array
ä          :Consecutive pairs
 n         :Reduced by inverse subtraction
  T        :After first prepending 0
    f      :Filter elements by
     ¬     :Square root (The square root of a negative being NaN, which is falsey)
           :Implicitly reduce by addition and output

6 bytes

Nice one, @Oliver; wouldn't have thought of that.

Common Lisp, 88 87 bytes
(lambda(s)(let((o 0))(dolist(c s)(incf o(max 0 c))(mapl(lambda(y)(decf(car y)c))s))o))

non-minified
(lambda (skyline)
  (let ((output 0))
    (dolist (current-skyscraper-height skyline)
      (incf output (max 0 current-skyscraper-height))
      (mapl (lambda (skyscraper)
              (decf (car skyscraper) current-skyscraper-height))
            skyline))
    output)))

Test it
When one tower is painted, it takes a number of brushstrokes equal to it's height.  These brushstrokes translate to all the following ones, which is indicated here by subtracting the current tower's height from all other towers (and itself, but that doesn't matter).  If a following tower is shorter, then it will be pushed to a negative number, and this negative number will subsequently subtracted from the towers that follow (indicating brushstrokes that could not be translated from a previous tower to the next ones).  It actually just subtracts the number from all tower heights, including previous ones, but this doesn't matter because we don't look at the previous ones again.

Welcome to PPCG. Could you possibly provide a link to an online testing environment for ease of verification?

Yes, absolutely. https://rextester.com/TKBU14782 The answer will be updated shortly

Well done. +1 for a nice, working first post. Have fun golfing.

Husk, 4 bytes
ΣẊ>Θ

Try it online!
Uses the same algorithm as everybody else (see here for an explanation), it just does so with fewer bytes than anybody else :D
Explanation
ΣẊ>Θ
   Θ    Prepend a 0 to the values
 Ẋ      For each pair of adjacent values (a,b)
  >     Return b-a if b>a else 0
Σ       Sum all of these values

> in Husk does a great job for this task: it does return a truthy value iff b>a, but this truthy value also happens to be the difference b-a, accomplishing two tasks in one go!

05AB1E, 13 10 bytes
Z>Lε@γPO}O

Try it online or verify all test cases.
Explanation:
Z            # Get the maximum of the (implicit) input-list
 >           # Increase it by 1 (if the list only contains 0s)
  L          # Create a list in the range [1, max]
   ε         # Map each value to:
    @        #  Check if this value is >= for each value in the (implicit) input
     γ       #  Split into chunks of adjacent equal digits
      P      #  Take the product of each inner list
       O     #  Take the sum
        }O   # And after the map: take the sum (which is output implicitly)

Retina 0.8.2, 21 bytes
\d+
$*
(1+)(?=,\1)

1

Try it online! Link includes test cases. Explanation:
\d+
$*

Convert to unary.
(1+)(?=,\1)

Delete all overlaps with the next tower, which don't need a new stroke.
1

Count the remaining strokes.

Nekomata, 5 bytes
ç-P‼∑

Attempt This Online!
A port of @Arnauld's 05AB1E answer.
ç-P‼∑
ç           Prepend zero
 -          Minus to get the delta
  P‼        Filter by positive
    ∑       Sum

Thunno 2 S, 6 5 bytes
0ƤṢ0§

Attempt This Online!
Port of @Arnauld's 05AB1E answer.
-1 thanks to @alephalpha
Explanation
0ƤṢ0§   # Implicit input
0Ƥ      # Prepend a 0
  Ṣ     # Compute deltas
   0§   # Maximum with 0
        # S flag sums the list
        # Implicit output

-1 byte: 0ƤṢ0§.

@alephalpha thanks, updated

Perl 5, 21 bytes
$\+=$_>$'&&$_-$';//}{

TIO
How

-p + }{ + $\ trick
// matches empty string so that for next line postmatch $' will contain previous line
$\+=$_>$'&&$_-$' to accumulate difference between current line and previous if current is greater than previous, (could also be written $\+=$_-$' if$_>$', but perl doesn't parse $\+=$_-$'if$_>$' the same)

C# (Visual C# Interactive Compiler) with flag /u:System.Math, 47 bytes
n=>n.Select((a,i)=>i<1?a:Max(a-n[i-1],0)).Sum()

Try it online!
Old version, with flag /u:System.Math, 63 bytes
n=>n.Aggregate((0,0),(a,b)=>(a.Item1+Max(0,b-a.Item2),b)).Item1

I feel like this solution is more elegant than the first one. It goes through the array with a two-value tuple as a starting value, picking up values, and stores the value before it in the second part of the tuple.
Try it online!

Pyth, 8 bytes
s>#0.++0

Yet another port of @tsh's marvellous answer. Takes the sum (s) of the positive values (>#0) of the deltas (.+) of the input with 0 prepended (+0Q, trailing Q inferred).
Try it online here, or verify all the test cases at once here.
String joining method, 10 bytes
This was the solution I wrote before browsing the other answers.
lcj.t+d*LN

Test suite.
lcj.t+d*LNQ   Implicit: Q=eval(input()), b=<newline>, N=<quote mark>
              Trailing Q inferred
        L Q   Map each element of Q...
       * N    ... to N repeated that many times
     +b       Prepend a newline
   .t         Transpose, padding with spaces
  j           Join on newlines
 c            Split on whitespace
l             Take the length, implicit print

Wolfram Language (Mathematica), 34 bytes
A port of @Arnauld's solution.
Tr@Select[{##,0}-{0,##},#>0&]&@@#&

Try it online!

Alternate 37-byte solution using the Factor algorithm's technique: https://tio.run/##y00syUjNTSzJTE78n2b7PyS/JDEnWrnON7GizkBN30FDWbfaoLbOKz8zr843v7jEQVkzVu1/QFFmXkl0mkO1oY6xjpGOIRibAtnGOiY6RrWx/wE

Clojure, 50 bytes
#((reduce(fn[[s n]i][(+(max(- i n)0)s)i])[0 0]%)0)

Try it online! (Why doesn't this print anything?)
#( ; begin anonymous function
    (reduce
        (fn [[s n] i] ; internal anonymous reducing function, destructures accumulator argument into a sum and the previous item
            [(+ (max (- i n) 0) s ; the sum part of the accumulator becomes the previous sum plus the larger of zero and the difference between the current number and the last one, which is how many new strokes need to be started at this point
            i]) ; ...and the previous item part becomes the current item
        [0 0] ; the initial value of the accumulator gives no strokes yet, and nothing for them to cover yet
        %) ; reduce over the argument to the function
    0) ; and get the sum element of the last value of the accumulator.

Welcome to PPCG! I don't know anything about Clojure, but a quick search shows that you'll need to evaluate the lazy for loop. Try it Online! (Tip: you can use the link button to auto-format your answer). Hope you stick around and have some fun!

Java (JDK), 57 bytes
a->{int s=0,p=0;for(int x:a)s-=(x>p?p:x)-(p=x);return s;}

Try it online!
Another port of tsh's Javascript answer. So make sure you've upvoted them.
Note that I used subtraction instead of addition because it allowed me to write (p=x) as right operand in the same statement.

Factor + math.unicode, 24 bytes
[ dup 0 prefix [v-] Σ ]

Try it online!
Explanation
         ! { 10 9 8 9 }
dup      ! { 10 9 8 9 } { 10 9 8 9 }
0        ! { 10 9 8 9 } { 10 9 8 9 } 0
prefix   ! { 10 9 8 9 } { 0 10 9 8 9 }
[v-]     ! { 10 0 0 1 }  (subtract two vectors, clamping negative numbers to 0)
Σ        ! 11

Kotlin
fun f(test:IntArray):Int{var s=0;var p=0;test.forEach{val f=(if(it>p)p else it);p=it;s-=f-p};return s}

Try it yourself

Since this is a [tag:code-golf] question, you are required to golf your answer i.e. Make it as short as possible , removing whitespace and inlining variable values. You can check the tips for Kotlin here  to improve your answer further.

Arturo, 35 33 bytes
$=>[l:0sum map&'x[max@[0x-l]l:x]]

Try it

Uiua, 11 bytes
/+↥0-↘¯1⊂0.

Try it!
Port of tsh's JavaScript answer.
/+↥0-↘¯1⊂0.
          .  # duplicate
        ⊂0   # prepend a zero
     ↘¯1     # drop last element
    -        # subtract the two arrays
  ↥0         # change negative numbers to zero
/+           # sum

Stax, 8 bytes
Φ┐Γ╟φφ.╨

Run and debug it
Uses the widely used approach from tsh's JavaScript solution.

MATL, 15 14 13 bytes
ts:<~"@Y'x]vs

Input is a column vector, using ; as separator.
Try it online! Or verify all test cases.
Explanation
t       % Implicit input: column vector. Duplicate
s       % Sum
:       % Range from 1 to that. Gives a row vector
<~      % Greater or equal? Element-wise with broadcast
"       % For each column
  @     %   Push current columnn
  Y'    %   Run-length encoding. Gives vector of values (0, 1) and vector of lengths
  x     %   Delete vector of lengths
]       % End
v       % Vertically concatenate. May give an empty array
s       % Sum. Implicit display