Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdio>
- #include <vector>
- #include <utility>
- #include <cstring>
- using namespace std;
- int n,m;
- int graph[101][101];
- bool visited[101];
- int dist[101];
- int source[101];
- vector<pair<int,int> > used;
- int doMST(bool record)
- {
- memset(visited,0,sizeof(visited));
- for(int i = 0 ; i < 101 ; ++i)
- dist[i] = 99999999;
- dist[1] = 0;
- int totalCost = 0;
- for(int i = 0; i < n ; ++i)
- {
- int smallest = -1;
- for(int j = 1 ; j <= n ; ++j)
- if(!visited[j] && (smallest == -1 || dist[smallest]>dist[j]))
- smallest = j;
- visited[smallest] = true;
- // printf("Next smallest is %d with dist %d\n",smallest,dist[smallest]);
- if(record && smallest != 1)
- used.push_back(make_pair(smallest, source[smallest]));
- // printf("Connected %d with %d\n",smallest,source[smallest]);
- totalCost += dist[smallest];
- for(int j = 1 ; j <= n ; ++j)
- if(graph[smallest][j] != -1)
- if(graph[smallest][j] < dist[j])
- {
- dist[j] = graph[smallest][j];
- source[j] = smallest;
- }
- }
- return totalCost;
- }
- int main()
- {
- memset(graph,-1,sizeof(graph));
- scanf("%d%d",&n,&m);
- for(int i = 0 ; i < m ; ++i)
- {
- int a,b,c;
- scanf("%d%d%d",&a,&b,&c);
- graph[a][b] = graph[b][a] = c;
- }
- printf("%d ",doMST(true));
- int best = 999999999;
- for(int i = 0 ; i < used.size() ; ++i)
- {
- int a = used[i].first;
- int b = used[i].second;
- // printf("%d - %d\n",a,b);
- int remember = graph[a][b];
- graph[a][b] = graph[b][a] = -1;
- best = min(best, doMST(false));
- graph[a][b] = graph[b][a] = remember;
- }
- printf("%d",best);
- return 0;
- }
Add Comment
Please, Sign In to add comment