Common BoardInstead of doing the cuts in the order given in the input, I found it easier to do it in reverse order, so we get merging instead of cutting. Edited by author 29.03.2023 21:05 #include<bits/stdc++.h> using namespace std; #define endl "\n" #define int long long #define mod 1000000007 #define maxn 10010 #define pb push_back #define mp make_pair #define fi first #define se second #define inf 100000000000 vector<pair<int, int>> adj[maxn]; int n, m; // struct node //for edges // { // int pos, dir, dist; // node(){}; // node(int _pos, int _dir) // { // pos = _pos; // dir = _dir; // } // }; int go(int s, int e) {
int dist[maxn][2]; for(int i=0; i<maxn; i++) { for(int j=0; j<=1; j++) { dist[i][j] = inf; } } deque<pair<int, int>> q; //pair->{node, edgedir} //making direction list here, q.push_back({s, 0}); //0->outgoing to node s dist[s][0] = 0; q.push_back({s, 1}); //1->incoming from node s dist[s][1] = 0; while(!q.empty()) { pair<int, int> cur = q.front(); //node int v = cur.first; int dir = cur.second; //dist int dv = dist[v][dir]; //guarenteed that shortest dist till cur node has been calc already q.pop_front(); //if(dv == inf) break;
if(cur.first == e) return dv; //gauarenteed via djikstra that this willbe minimest
//relax all the neighbours, and as you relax one , push into minheap the nodes for(auto it: adj[v]) { int to = it.fi; int dir2 = it.se; //previous //note that for type edge dir, you have relax for all neighbouring nodes int dist2=0; if(dir2 == dir) { dist2 = dist[v][dir2]; //dist[to][dir2] = min( dist[to][dir2], dist[v][dir2] ); } else dist2 = dist[v][dir] + 1; // dist[to][dir2] = min( dist[to][dir2], dist[v][dir] + 1);
//only relax and add to queue, if less than prev distance to this node if(dist2 < dist[to][dir2]) { if(dist2 <= dv) //less than equal to cur_dist q.push_front({to, dir2}); else q.push_back({to, dir2});
dist[to][dir2] = dist2;
}
} } return -1; } void solve() { cin>>n>>m; for(int i=1;i<=m;i++) { int x, y; cin>>x>>y; adj[x].pb({y, 0}); adj[y].pb({x, 1}); } int s, e; cin>>s>>e; //cout<<"hi"; int ans = go(s, e); cout<<ans<<endl; } signed main() { int t=1; //cin>>t; while(t--) { solve(); } return 0; } I do not understand the final push back and front part. Why to push only if dist is less than dv? Why are we comparing it to dv? If it is for the right position in the queue of the pushed element(like in 0-1 bfs),then how do we know that the queue only has 0-1? That is the underlying part of the 0-1 bfs right?else it is dijkstra. I think the queue has difference of 1 between its min and max. Can you tell what all is true and exactly what is happening. I would really appreciate. Thank you Edited by author 04.05.2020 20:46 Edited by author 04.05.2020 20:47 if(dist2 <= dv) //less than equal to cur_dist q.push_front({to, dir2}); else q.push_back({to, dir2}); CAN YOU EXPLAIN ME THIS PART WHY DIST 2 GREATER IS PUSHED BACK NOT IN FRONT AND VICE VERSA WHAT I MEAN TO KNOW IS WHY WE COMPARE CONNECTED VERTEX DISTANCE Я решил задачу с помощью графа, где вершинки - состояния ёмкостей,и рассмотрел из очередного состояния все переходы, запоминая те состояния ,где уже был. Но я никак не могу оценить кол-во возможных состояний. Может кто-нибудь подскажет как оценить? Самая грубая оценка - у нас есть числа a,b,c>=0 и a+b+c=N(для случая,когда не подливаем и не выливаем-в этом случае сумма константа). Тогда количество таких чисел O(N^3),но это ужасная оценка. Согласен, было бы интересно узнать максимальное количество возможных состояний и при каких значениях a,b,c оно достигается Edited by author 16.11.2019 13:00 Можно оценивать так: пусть ёмкости не превосходят значения C. Рассмотрим возможные переходы между состояниями. 1) Когда подливаем из заправки в канистру. Тогда канистра, в которую подливаем, становится полной. 2) Когда переливаем между канистрами. Тогда либо канистра, в которую переливаем, становится полной, либо канистра, из которой переливаем, становится пустой (либо и то, и то). Получается, что в каждом состоянии хотя бы одна канистра либо пустая, либо полная. Тогда количество состояний можно оценить как 6*(С+1)^2, то бишь O(C^2). First I used Kruskal algo but got WA9 verdict. My program didn't give right answer for next test: 4 1 4 0 1 1 100000 1 0 1 100000 1 1 0 100000 100000 100000 100000 0 right answer: 100002 Implementation of Prim algo gave the correct answer at last. HM, i have right output on this test, but WA 9 This test helped me.... 5 2 1 3 0 1 2 3 4 1 0 2 3 4 2 2 0 3 4 3 3 3 0 4 4 4 4 4 0 =8 (I was getting 9). Basically my algorithm (roughly Prim's) tried to short-cut checking vertex weights. For any node, make sure you check verices to ALL nodes.... HM, i have right output on this test, but WA 9 Some tests: 4 2 1 4 0 4 8 9 4 0 2 7 8 2 0 1 9 7 1 0 Answer 3 4 2 1 3 0 6 7 8 6 0 2 3 7 2 0 4 8 3 4 0 Answer 5 Edited by author 27.10.2015 20:10 5 3 1 3 2 0 1 2 3 4 1 0 2 3 4 2 2 0 3 4 3 3 3 0 4 4 4 4 4 0 answer is 7 Edited by author 19.02.2019 12:09 One more test that helped me to find my error for WA #9. 5 2 1 5 0 1 100 150 200 1 0 10 50 200 100 10 0 11 100 150 50 11 0 2 200 200 100 2 0 Answer: 13 c[i][j] = c[j][i] This is wrong test input: 2 b 1 a 1 2 a b output: a [empty] b hope can help you! GOOD LUCK! also, it has more than 10 matches New tests were added. All accepted solution were rejudged, ~4% of them lost their accepted status It can be at least 3 lines of code if you write one statement per line (in plain C) double k1, k2, k3; scanf("%lf %lf %lf", &k1, &k2, &k3); printf("%.0lf", /* The Expression */); Edited by author 24.03.2023 00:40 не могу найти ошибку,возможно ли узнать какие числа вбивает 8-й тест? Только это называется не "ошибка в 8-м тесте" (сам тест корректен), а "ошибка *в решении* НА 8-м тесте". Тест - просто случайный тест, направленный на убивание жадных решений. Эту задачу неверно решать жадным алгоритмом. тест не случайный, так как при разных алгоритмах ошибки всегда под одними и теми же номерами Check if your input correctly outputs the last word, if the last character is latin. The first test ends with a . Edited by author 21.03.2023 18:29 input: 6 3 8 1 0 2 0 3 0 4 0 5 1 7 1 10 1 12 1 output: No reason 1 10 2 5 3 12 4 7 What is in test 3????? I dont know, but if you are using BFS in your solution, you should remember, that graph can contain more than 1 connected component. Try this test: 6 2 3 0 0 0 5 6 0 0 0 one of answers: 011100 тест неверный, по условию можно в любую страну перейти, а у вас например из 1 в 4 не перейти //Don't ask me. I don't know. Just work. If anybody can tell me why for (int i = k + 7; i >= 0; i--) and why we needn't n%k - Please, tell! I don't understand. using System; namespace ConsoleApp32 { class Program { static void Main(string[] args) { string[] vvod = Console.In.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); int n = int.Parse(vvod[0]); string k1 = vvod[1]; int k = k1.Length; int q = 1; for (int i = k + 7; i >= 0; i--) { int t; t = n - i * k; if (t > 0) q *= t; } Console.WriteLine(q); } } } Edited by author 13.01.2018 23:49 because we have more than 1x! (minimum 2) and less or exactly 9 (because we have 9 numbers 2...10 and it nevermind if we have more !...! than 9). so we have k = 9-2 =7 (maximum) if we use % and the number of '!' is > 10 we have wrong answer, because we have zero: x%y=0 Edited by author 19.03.2023 19:49 Make sure your code can choose devices other than the 1st one from the list... Why does this code throw a runtime error? Everything is right!! from sys import stdin pocht_1 = ["A", "P", "O", "R"] pocht_2 = ["B", "M", "S"] pocht_3 = ["D", "G", "J", "K", "T", "W"] count = 0 mesto = 1 for i in sys.stdin.split("\n")[1:]: if i[0] in pocht_1: if mesto == 3: count += 2 elif mesto == 2: count += 1 mesto = 1 elif i[0] in pocht_2: if mesto == 1: count += 1 elif mesto == 3: count += 1 mesto = 2 else: if mesto == 1: count += 2 elif mesto == 2: count += 1 mesto = 3 print(count) 1 2 0 0 0 0 0 0 3 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2.24 My solution is 20 lines. Easy problem. 14 lines solution with using recursive function. I have recursive function too. Whatever, Good Job! 7 lines with recursive func in python 3. Or 14 with normal look a code. All operations except clone work O(1) in my program, but clone works in O(n). Despite that fact, my solution works in 0.218s New tests were added. Thank you. Edited by author 27.09.2020 14:29 Tests not check memory leaks, but check amount of used memory... Its weard. If you dont copy robot's stacks and just relink pointers, tests not check that you have lost memory Case Learn 1 1 Learn 1 2 .... Learn 1 n Clone 1 Rollback 1 Rollback 2 .... Rollback 1 Rollback 2 Learn 1 1 ... Learn 1 n In my solution in the end youll have n losted elements and n new elements in 1 robot that is assimptotically equal to copy all stacks Read problem statement more closely. The graph can be disconnected. Read problem statement more closely. The graph can be disconnected. Really helped me a lot. |
|